supporting runtime baseURL/publicPath

Description

Nuxt doesn’t allow the publicPath (CDN url) to be overridden at run time – it’s baked into the manifest at
build time. This hook intercepts the VueRenderer when it has loaded the manifest and updates the publicPath
to the current env value.

The problem is that i have a single build (i.e 1 docker image) that is used on multiple environments. Each user should be able to specify their own router base as an .env variable and just run the container without the need to rebuild the image.
Nuxt resources are then can’t be found (nuxt .js files).

When building and running for the first time (nuxt build && nuxt start) everything works normally. Then changing the BASE value in the .env file breaks the app.

Solution description

Setting the baseURL anew on runtime

Describe alternatives you’ve considered

.env:

BASE=\rotem\

nuxt.config.js:

  publicRuntimeConfig: {
    baseURLSubDirectory: process.env.BASE_URL_SUB_DIRECTORY,
  },
  router: {
    base: process.env.BASE_URL_SUB_DIRECTORY
  },
  plugins: [
    {
      src: '@/plugins/cdn.js',
      ssr: false
    },
  ],
  hooks: {
    /* Nuxt doesn't allow the publicPath (CDN url) to be overridden at run time - it's baked into the manifest at
    ** build time.  This hook intercepts the VueRenderer when it has loaded the manifest and updates the publicPath
    */ to the current env value.
    render: {
      resourcesLoaded(resources) {
        const path = `${process.env.BASE_URL_SUB_DIRECTORY}_nuxt/`
        resources.clientManifest && (resources.clientManifest.publicPath = path)
        resources.modernManifest && (resources.modernManifest.publicPath = path)
        resources.serverManifest && (resources.serverManifest.publicPath = path)
      }
    }
  }

plugins\cdn.js:

export default function({$config}) {
  if (process.client) {
    __webpack_public_path__ = `${$config.baseURLSubDirectory}_nuxt/`
  }
}

Build nuxt for production and then change .env:

BASE=\xrotem\

Then run the nuxt app.
The code replaces all resources on run-time! which is important but still i get a 404 page even though nuxt is able to find all the needed resources.

2 thoughts on “supporting runtime baseURL/publicPath

  1. Thanks for making issue @rotemrevivo91. It is indeed an important feature that we can have with runtimeConfig. Workaround seems good but it can be easily broken by internal changes of either nuxt or vue-bundle-renderer… So should support a runtime config like this:

    {
      publicRuntimeConfig: {
        baseURL: process.env.NUXT_BASE_URL
      }
    }

    Still some modes like static target cannot support as we directly use inside templates.