Search code examples
dotenvsveltekit

How to use dotenv in SvelteKit project?


I'm trying to use dotenv.config() in a SvelteKit project.

I can run npm run build successfully. But when I try to start the server (using node build), it throws Error: Dynamic require of "fs" is not supported.

I tried to comment out the dotenv part in src/routes/test.js and build again, and this time the server started without any errors. (I created the project with npm init svelte@next without typescript, and except for the codes here, nothing else is changed)

How should I use dotenv here to load environment variables at runtime?

svelte.config.js

import node from '@sveltejs/adapter-node';

const config = {
    kit: {
        adapter: node(),
        target: '#svelte'
    }
};

export default config;

/src/routes/test.js

import dotenv from 'dotenv';

dotenv.config();

export function get() {
    return {
        body: {
            test: process.env.TEST
        }
    }
}

.env

TEST=123

Solution

  • Since a few weeks SvelteKit has a built-in way to handle environment variables: https://kit.svelte.dev/docs/modules#$env-dynamic-private