sveltesveltekitsvelte-5

.env files in production using adapter-node (pre-built application)


I am trying to deploy a sveltekit app using adapter-node using .env files.

I have a .env file with several values:

V_TEST1=TEST1
PUBLIC_V_TEST2=TEST2

I access them using import { V_TEST1 } from '$env/static/private'; and import { PUBLIC_V_TEST2 } from '$env/static/public';

In development, I have no issues. The values get read and used.

When deploying, there are 2 ways of doing this, one is to build on development side and deploy the necessary files or build server side, sending the whole code to the server and build on the server.

If I build server side, I am able to access the .env I place on the server (different that dev .env) and have no issues. But I do not want to build on the server.

If I build on development side. The environment variables seem to be hard coded into the /build and if I place a .env on the server, the file gets ignored.

On the server I am running using node --env-file=.env build as recommended on sveltkit docs https://svelte.dev/docs/kit/adapter-node#Environment-variables.

So is there a way of accessing the .env files on the server on a pre-build application?


Solution

  • You have to switch to the $env/dynamic/* modules if you want to access variables that are loaded when running the application. (Variable access is a bit different via an env object, see docs.)