Because SvelteKit comes with Vite, using .env may be a bit unfamiliar. There are two ways to go about it, either with Vite's import.meta.env out of the box or with the usual suspect process.env that requires a bit more setting up.
You may also be interested in
SvelteKit + TailwindCSS
SvelteKit + Heroku
Using import.meta.env
Full information is available in the official docs but the gist of it is that you should prefix any variable that you want exposed to your client with VITE_
It means import.meta.env.FOO will not be exposed client-side, while import.meta.env.VITE_FOO will be.
.env
FOO=BAR
VITE_FOO=BAR
browser
console.log(import.meta.env.FOO)
// undefined
console.log(import.meta.env.VITE_FOO)
// BAR
Using process.env
If for some reason you still want to use process.env, because you're used to it or you don't feel like renaming all your variables VITE_SOMETHING, you can also do it with the env-cmd package.
npm i env-cmd
Then modify your config in svelte.config.js
svelte.config.js
const config = {
kit: {
vite: {
define: {
'process.env': process.env,
},
},
},
};
And finally add env-cmd to your dev script
package.json
{
"scripts": {
"dev": "env-cmd svelte-kit dev",
},
}
And now you'll be able to access process.env in your client
.env
FOO=BAR
browser
console.log(process.env.FOO)
// BAR
Top comments (1)
I guess the env-cmd can be replaced with dotenv