DEV Community

Nostro
Nostro

Posted on • Updated on

Using environment variables with SvelteKit

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
Enter fullscreen mode Exit fullscreen mode

browser

console.log(import.meta.env.FOO)
// undefined


console.log(import.meta.env.VITE_FOO)
// BAR
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Then modify your config in svelte.config.js

svelte.config.js

const config = {
    kit: {    
        vite: {
            define: {
                'process.env': process.env,
            },
        },
    },
};
Enter fullscreen mode Exit fullscreen mode

And finally add env-cmd to your dev script

package.json

{
    "scripts": {
        "dev": "env-cmd svelte-kit dev",
        },
}
Enter fullscreen mode Exit fullscreen mode

And now you'll be able to access process.env in your client

.env

FOO=BAR
Enter fullscreen mode Exit fullscreen mode

browser

console.log(process.env.FOO)
// BAR
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

Collapse
delanyoyoko profile image
delanyo agbenyo

I guess the env-cmd can be replaced with dotenv