Tim Deschryver

Environment variables with SvelteKit

Published
@tim_deschryver

When the beta version of SvelteKit was announced, I immediately got excited and migrated my blog from Sapper to SvelteKit. Overall, the migration was very smooth and quick. The big reason why this went smooth is that the API is almost identical, and the docs and examples were helpful.

I just stumbled upon one problem with environment variables. Sadly, it doesn't seem to have an easy fix, that's why I decided to write down a workaround (based on the answers given in that Github issue).

Define Environment Variables

SvelteKit delegates its build step to Vite, which supports environment variables. To define environment variables, we must use the dotenv module.

For example, to define a base path, we need to add the variable to a .env.* file. Note that all environment variables must be prefixed with VITE_, otherwise, the variables won't be exposed due to security reasons.

When the environment variable is defined, we can now use the import.meta.env.VITE_PUBLIC_BASE_PATH variable in our code. These variables will be replaced by their corresponding values.

The Problem

But as I mentioned before, there's one problem. When the application is served you don't notice the issue, but with the build command, the following error is thrown when the component file (which uses an environment variable) includes a style tag.

The Workaround

The workaround to this problem is to extract the environment variables into a separate module. Next, you can simply import the environment variable into your component from this module.

TypeScript Support

Lastly, you can make the environment variables type-safe by adding their types to the global.d.ts declaration file.


Please consider supporting me if have you enjoyed this post and found it useful:

Buy Me A Coffee PayPal logo
Support the blog Share on Twitter Discuss on Twitter Edit on GitHub