PrestonDocks
PrestonDocks

Reputation: 5408

sveltekit api process.env.VARIABLE_NAME undefined

I'm not sure if this is a race condition, but I am unable to access specific environment variables

I have an API endpoint setup in svelte

import dotenv from 'dotenv';
dotenv.config();
console.log(process.env)
console.log(process.env.NODE)

Result is

{
  NVM_INC: '/Users/simon/.nvm/versions/node/v16.13.1/include/node',
  TERM_PROGRAM: 'vscode',
  NODE: '/Users/simon/.nvm/versions/node/v16.13.1/bin/node',
  INIT_CWD: '/Users/simon/development/svelte/sveltekit-oidc',
  NVM_CD_FLAGS: '-q',
  TERM: 'xterm-256color',
  ...
}
undefined

On further testing the following works OK

console.log(process.env['NODE'])
/Users/simon/.nvm/versions/node/v16.13.1/bin/node

Not sure why this is and it worries me that if this is a race condition, it may work in development and at some point give me errors in production.

Upvotes: 1

Views: 2565

Answers (1)

Shriji Kondan Elangovan
Shriji Kondan Elangovan

Reputation: 1099

For sveltekit you need to prefix the variables in the .env file with for example, VITE_MYSECRET=123 and use/import them using import.meta.env.VITE_MYSECRET.

Reference documentation https://kit.svelte.dev/faq#env-vars and https://vitejs.dev/guide/env-and-mode.html#env-files.

For Svelte you need rollup-replace plugin to pick up environment variables, the below snippet was answered on another question.

import { config } from "dotenv";
...
replace({
      values: {
        foo: JSON.stringify({ bar: "Hello", ...config().parsed }),
      },
    })
...

and in your .svelte file

  const { bar, ...rest } = foo;
  console.log("bar=>", bar);
  console.log("env=>", rest);

Upvotes: 2

Related Questions