Nuxt SSR rebuild of routes.json on the fly (production)

Viewed 360

I'm pretty sure the answer to this is no...but is there any way to initiate a rebuild of .nuxt/routes.json and .nuxt/router.js file on the fly, while the production server is running from within native nuxt functionality. nuxt.config.js router.extendRoutes builds the routes at the initial build time - haven't found a way of doing an update while the server is still running. Would prefer not to have to do a new npm build.

// Router middleware
router: {
    middleware: ['router-agent', 'ssr-promises'],
    async extendRoutes (routes, resolve) {
        // pulls in routes from external file
        await customRoutes(routes, resolve)
    }
},

We have a selection of custom routes we need to build from a CMS

// extendRoutes snippet
let pageRoutes = require('./routes-bkp.json')

try {
  const { data: { pages } } = await getPagesForRoutes.queryCMS()
  pageRoutes = pages
  console.log('Route Request Succeeded.')
} catch {
  console.log('Route Request Succeeded.!  Using backup version.')
}

pageRoutes.forEach(({ slug }) => {
  routes.unshift({
    name: slug,
    path: `/:page(${slug})`,
    component: '~/pages/_page'
  })
})

The purpose of all this is have a client build trigger in the CMS, when they update their pages.

More info about router.js here: https://nuxtjs.org/docs/directory-structure/nuxt

and about extending the router here: https://nuxtjs.org/docs/features/file-system-routing/#extending-the-router

1 Answers

build.watch might assist you to trigger a server restart on a file change.

You can also generate a json file on the server that will contain information about the dynamic routes of your CMS, import that file in your extendRoutes and build.watch that file in case it doesn't trigger a restart when it's changed

For production, you can use nuxt programmatically to expose a server middleware that listens to requests and restarts the server

Related