When using environment variables in web apps, we use it as process.env.YOUR_ENV
in most cases.
I wrote about deploying SvelteKit app with Vercel in the previous post.
In this post, I tell you about using environment variables in SvelteKit and using them in Vercel as process.env
.
1. Create a .env
file
At first, create a .env
file in your project root and then add some variables. For example:
1 | // .env |
Note that you should add prefix VITE_
to your variables. This is because SvelteKit uses Vite under the hood.
I recommend you add .env
to .gitignore
by the way.
2. Using environment variables in SvelteKit
Convert variables so that it can be used in your project.
For example, create Env.js
in lib
directory and declare them.
Note that the file name(here Env.js
) is arbitrary, but not a .svelte
file.
1 | // src/lib/Env.js |
import.meta.env
is the object in Vite.
You can now use them in your project.
1 | // sample.svelte |
3. Using them as process.env
in Vercel app
To use your environement variables as process.env
in Vercel, you should add the setting in svelte.config.js
,
1 | // svelte.config.js |
Check the following settings compilerOptions.paths
of jsconfig.json
. If not, add it.
1 | // jsconfig.json |
Finally, although I don’t know this is the best practice, use them as follow for instance:
1 | // sample.svelte |
4. Configuration in Vercel
*See this article for how to deploy your app in Vercel.
Add your environment variables in the Vercel Settings.
5. Done
You can now use process.env
in SvelteKit app hosted with Vercel.