node.jsdockervue.jsenvironment-variablesnuxt.js

Nuxt3: How to set runtime environment variables after docker build via process.env


My nuxt3 app works great if I build & run it locally with docker-compose and environment variables.

But when I push the built docker image to my remote production environment I'm not able to apply the production environment variables in the runtimeConfig. Probably because process.env["SECRET_KEY"] gets replaced with "the real secret key" during the build phase.

If I name environment variables NUXT_PUBLIC_XXXX / NUXT_XXXX, I'm able to update runtimeConfig even after building the image.

But as I use a PaaS Service for my production deployment, I am not in control of the variable naming. Therefore I'm unable to dynamically provide the right runtime config for my remote environment -> I always end up with the local values which were set during the build phase on my local machine. (see clientID in example below)

Is there a way how to set the runtime config via process.env["custom env name"] even after the image was built? Or do you have any other idea how to dynamically provide the runtime config? (I'd like to avoid building separate containers for each environment

Thx a lot for your inputs. Any help is highly appreciated!

#nuxt.config.ts
...
runtimeConfig: {

#in production ENVs are accessible under the key "VCAP_SERVICES", if key is not present the local development env is applied
clientId: process.env["VCAP_SERVICES"] ? process.env["VCAP_SERVICES"]["clientId"] : process.env["UAA_CLIENT_ID"],
secretKey: process.env["NUXT_SECRET_KEY"]

  public: {
    backendApi: 'http://127.0.0.1:5000',  // will be overridden by NUXT_PUBLIC_BACKEND_API environment variable
    environment: "production", // will be overridden by NUXT_PUBLIC_ENVIRONMENT environment variable
        }
    },

Solution

  • It is possible to provide environment variables at runtime (after building the docker image) but only if adhere to the following requirements (see Nuxt Docs)

    Runtime config values are automatically replaced by matching environment variables at runtime. There are two key requirements.

    1. Your desired variables must be defined in your nuxt.config. This ensures that arbitrary environment variables are not exposed to your application code.
    2. Only a specially-named environment variable can override a runtime config property. That is, an uppercase environment variable starting with NUXT_ which uses _ to separate keys and case changes..