Environment variables with SvelteKit

profile
Tim Deschryver
timdeschryver.dev
format_quote

⚠️ Update: SvelteKit now supports environment variables, making this post obsolete. For more info see the documentation on: $env/dynamic/private, $env/dynamic/public, $env/static/private, and $env/static/public. Thanks for the heads-up Josh Habdas.

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 link

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 link

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 link

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 link

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

Feel free to update this blog post on GitHub, thanks in advance!

Join My Newsletter (WIP)

Join my weekly newsletter to receive my latest blog posts and bits, directly in your inbox.

Support me

I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.

Buy Me a Coffee at ko-fi.com PayPal logo

Share this post