Search code examples
typescriptenvironment-variablessveltekit

How to use environment variables in root files of you SvelteKit project?


I have a SvelteKit project using TypeScript with a .env file at the root. At the root I added a drizzle.config.ts file. When I add the following on top:

_import { DATABASE_HOST} from '$env/static/private';_

then both WebStorm and VSCode give me the following error:

_Cannot find module '$env/static/private' or its corresponding type declarations._

This also happens when I start a completely new SvelteKit project and add the files as mentioned above, so I suppose it would be easy to reproduce the issue.

I've restarted VsCode, Webstorm and my computer. I've tried to do it using a new project. None of these things worked. Many posts tell me to change some configurations files. I tried some of these but they didn't work. I also feel like that shouldn't be the solution since there should be an out of the box solution?

Could anyone explain why this does not work, and what the right way would be to use Environment variables in root files in SvelteKit?

Thanks in advance!


Solution

  • You can only use the $env modules in the code of the SvelteKit application (generally things in src) because that is processed by the build which injects the variables accordingly.

    In other files you have to use whatever mechanism your runtime executing the file provides for accessing environment variables, e.g. in Node there is process.env.