node.jsdockerenvironment-variablessveltekit

How to change environment variables at runtime in a SvelteKit App using the Node adapter?


I have a SvelteKit app that I am using with the Node adapter to run as a Node.js server. I would like to change the environment variables at runtime so that I can package the app into a container and provide the server address dynamically at startup.

Is there a recommended way to achieve this in SvelteKit with the Node adapter?

I followed the documentation and tried to use the following approach in my Dockerfile:

FROM node:23-alpine AS builder

WORKDIR /app

COPY . .

RUN npm install 
RUN npm run build --omit=dev
EXPOSE 3000

CMD ["node", "--env-file=.env", "build/index.js"]

Then, I ran the container with:

docker run -e VITE_BACKEND_URL="http://localhost:5062" -p 3000:3000 frontend

I expected that VITE_BACKEND_URL would be dynamically set at runtime, but instead, it appears that the environment variables are embedded during the build process and do not change when the container starts.

How can I properly configure my SvelteKit app with the Node adapter so that environment variables can be set at runtime instead of build time?


Solution

  • If you need dynamic environment variables, import them via $env/dynamic/private. (Anything from $env/static/* will be inlined into the code.)

    SvelteKit has its own method of managing private and public variables via the different modules. You probably should use those instead of the VITE_ prefix and import.meta.env.