Home > Back-end >  sveltekit api process.env.VARIABLE_NAME undefined
sveltekit api process.env.VARIABLE_NAME undefined

Time:12-20

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.

CodePudding user response:

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.

  • Related