Search code examples
node.jsdotenv

JavaScript dot notation does not work in process.env


Why can't I access process.env.TEST with dot notation, what is the difference between dot notation and brackets notation here?

.env:

TEST=123

src/routes/index.svelte:

<script>
import '$lib/test';
</script>

src/lib/test.js:

import dotenv from 'dotenv';
dotenv.config();

console.log(process.env.TEST, process.env['TEST']); // undefined 123

(I wrote the code in a new SvelteKit project, I did not change anything else except for the codes above)


Solution

  • SvelteKit is using Vite for bundling, right? It seems that Vite does "production replacement" for env variables: https://vitejs.dev/guide/env-and-mode.html

    Here is how import.meta.env variables are replaced:

    During production, these env variables are statically replaced. It is therefore necessary to always reference them using the full static string. For example, dynamic key access like import.meta.env[key] will not work.

    And plain access to process.env appears to be processed as well. For example, this source file:

    console.log('dot access', process.env.XDG_DATA_HOME);
    console.log('indexing env', process['env'].XDG_DATA_HOME);
    console.log('indexing var', process.env['XDG_DATA_HOME']);
    

    ...will be transformed by Vite to this:

    console.log("dot access", {}.XDG_DATA_HOME);
    console.log("indexing env", process["env"].XDG_DATA_HOME);
    console.log("indexing var", process.env["XDG_DATA_HOME"]);
    

    As you can see, the first line was transformed. This makes sense if you want to use env variables to parametrize/customize a web script, but not if you run a bundled script in NodeJS.

    As a workaround, use square brackets to access the env or the variable.

    Here is a tracking issue in Vite: https://github.com/vitejs/vite/issues/3229