Runtime Environment Variables for SvelteKit SSR

Proper environment variables for SvelteKit

Runtime Environment Variables for SvelteKit SSR
  • October 2022 - This article has been updated since it's first release to adhere to new conventions adopted by SvelteKit

SvelteKit introduced some new ways to run code server side, ensure certain code only runs server side, and natively support .env files (used only for convenience during development!). I'll show how to use environment variables, at runtime, and how to propagate them to the client when needed. This article assumes the adapteradapter-node is being used, but this process may work with other adapters.

Start the Dev Server

Let's make use of SvelteKit's generated types by starting the dev server

yarn dev

Create the Server Layout File

Create a file called +layout.server.ts under src/routes with the following contents.

Files named +layout.server.ts are run only the server allowing us to use environment variables.

The env module from $env/dynamic/private gives us access to runtime environment variables and allows us to use .env files while developing. It also provides some safety by failing imports to public code. You may use process.env instead which works fine, but I enjoy the guardrails and convenience of .env files in development without extra dependencies like dotenv, or env-cmd which I suggested in an earlier iteration of this article.

In our LayoutServerLoad function we're exporting an object called configuration with properties environment and displayEnvironment. These values will be available globally throughout the application since we've put them in the root server layout file. On pages, this object will be available via PageData.

Create the Svelte Layout File

Create a file called +layout.svelte under src/routes with the following contents.

Here we import data which holds our configuration object exported by the server layout's load function. We check if configuration.displayEnvironment is true and if so display the current environment we're running in from configuration.Environment.

Set the Environment Variables

While using the dev server we can make use of .env files. For production or other deployed environments we'd set them in the runtime environment just as the computer gods intentended.

Create a file called .env with the following

ENVIRONMENT=development
DISPLAY_ENVIRONMENT=true

Make sure .env is in your .gitignore, and to be nice to those who might fork your project create .env.example file with example values.

Check it out

Navigate to the running app in the browser and we should see what environment we're running in pulled from the environment variables.

DON'T RETURN SECRETS FROM LOAD FUNCTIONS!