1

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.

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.