Reputation: 37
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?
Upvotes: 0
Views: 51
Reputation: 37
Here’s a clear explanation of what I changed for anyone who might run into this problem.
Dockerfile:
# removed the "--env-file=.env"
CMD ["node", "build/index.js"]
Docker run is now:
docker run -p 3000:3000 -e PUBLIC_BACKEND_URL=http://localhost:5062 frontend
Code Changes:
import { env } from '$env/dynamic/public';
const backendUrl = env.PUBLIC_BACKEND_URL;
add .env to dockerignore and rename the env right from VITE_BACKEND_URL => PUBLIC_BACKEND_URL
Thanks a lot @brunnerh for your answer
I think you have to install Node 20.6+ or dotenv.
The official documentation for the solution is ENV and Node
Upvotes: 0
Reputation: 185280
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
.
Upvotes: 3