Environment Variables in SvelteKit and Vercel
FrontendWhen 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:
// .env
VITE_MY_API_KEY="<MY_API_KEY>"
VITE_MY_URL="<MY_URL>"
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.
// src/lib/Env.js
export const MY_API_KEY = import.meta.env.VITE_MY_API_KEY;
export const MY_URL = import.meta.env.VITE_MY_URL;
import.meta.env
is the object in Vite.
You can now use them in your project.
// sample.svelte
import { MY_API_KEY } from '$lib/Env';
console.log(MY_API_KEY);
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
,
// svelte.config.js
const config = {
kit: {
// ...
vite: {
define: {
'process.env': process.env,
},
},
}
};
export default config;
Check the following settings compilerOptions.paths
of jsconfig.json
. If not, add it.
// jsconfig.json
{
// ...
"compilerOptions": {
"baseUrls": ".",
"paths": {
"$lib": ["src/lib"],
"$lib/*": ["src/lib/*"]
}
},
// ...
}
Finally, although I don't know this is the best practice, use them as follow for instance:
// sample.svelte
import { MY_API_KEY } from '$lib/Env';
let myApiKey;
if (process.env.NODE_ENV === 'production') {
// For production
myApiKey = process.env.MY_API_KEY;
} else {
// For development
myApiKey = MY_API_KEY;
}
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.