Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem hosting Nuxt.js SSR app on Firebase

I'm trying to host a Nuxt.js app on Firebase, and I've followed this tutorial, and I got stuck at #10, when trying to do sudo firebase serve --only functions, hosting. I kept getting this Timed out waiting for function to respond..

Upon further investigating I found out that the problem is in /functions/index.js. The line nuxt.renderRoute('/').then(...) is taking forever to run, because the console.log('After render') is never called. Here's how the /functions/index.js looks like

/functions/index.js

const functions = require('firebase-functions')
const express = require('express')
const { Nuxt } = require('nuxt')

const app = express()

const config = {
  dev: false,
  buildDir: 'nuxt',
  build: {
    publicPath: '/public/'
  }
}
const nuxt = new Nuxt(config)

app.get('**', function (req, res) {
  res.set('Cache-Control', 'public, max-age=600, s-maxage=1200')
  console.log('it still works here')

  nuxt.renderRoute('/').then(result => {
    console.log(result.html)
    res.send(result.html)
  }).catch(e => {
    console.log(e)
    res.send(e)
  })
  console.log('After render')
})

module.exports.nuxtApp = functions.https.onRequest(app)

And this is how my terminal output looks like: enter image description here

like image 911
Chan Jing Hong Avatar asked Mar 15 '26 04:03

Chan Jing Hong


1 Answers

I am a little late, but glad to share my approach:

This is how my index.js looked like, after I got it to work with Firebase hosting. Note: I ended up taking an entirely different approach by simply using prerendering instead of ssr for hosting my nuxt app on firebase. However if you need to use SSR for your project, this works nicely:

const functions = require('firebase-functions')
const { Nuxt } = require('nuxt')
const express = require('express')
const admin = require('firebase-admin')

const app = express()

// Initialize Firebase (only if you use the Admin SDK, otherwise not needed)
admin.initializeApp({
  credential: admin.credential.cert(require('YOUR_KEY'))
});

// Nuxt Server Side Render Setup

const config = {
  dev: false
}

const nuxt = new Nuxt(config)

let isReady = false
const readyPromise = nuxt
  .ready()
  .then(() => {
    isReady = true
  })
  .catch(() => {
    process.exit(1)
  })

async function handleRequest(req, res) {
  if (!isReady) {
    await readyPromise
  }
  res.set('Cache-Control', 'public, max-age=1, s-maxage=1')
  await nuxt.render(req, res)
}

app.get('*', handleRequest)
app.use(handleRequest)
exports.nuxtssr = functions.https.onRequest(app)
like image 177
aside Avatar answered Mar 17 '26 18:03

aside



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!