Problem accessing env variables from VITE deploy
killhead
PROOP

4 months ago

Hi!

I created VITE widget as a service within railway problem.

In variables section there is VITE_TELEGRAM_BOT_TOKEN variable set, containing (obviously) a telegram token that I need to access in runtime.

const TELEGRAM_BOT_TOKEN = 
  import.meta.env.VITE_TELEGRAM_BOT_TOKEN || 
  (typeof window !== 'undefined' ? window.__TELEGRAM_BOT_TOKEN__ : '') || 
  '';

console.log('šŸ” [useTelegramAvatar] Environment check:', {
  hasToken: !!TELEGRAM_BOT_TOKEN,
  tokenLength: TELEGRAM_BOT_TOKEN.length,
  envMode: import.meta.env.MODE,
  allEnvVars: Object.keys(import.meta.env).filter(key => key.startsWith('VITE_')),
  windowToken: typeof window !== 'undefined' ? !!window.__TELEGRAM_BOT_TOKEN__ : 'N/A'
});

Expecting this code to get value of VITE_TELEGRAM_BOT_TOKEN, but it gets no info.

What am I doing wrong and how to fix this?

$5 Bounty

4 Replies

Railway
BOT

4 months ago

Hey there! We've found the following might help you get unblocked faster:

If you find the answer from one of these, please let us know by solving the thread!


clashing
FREE

4 months ago

Just try this:

const TELEGRAM_BOT_TOKEN = import.meta.env.VITE_TELEGRAM_BOT_TOKEN;
console.log("Token is", TELEGRAM_BOT_TOKEN);
console.log("Env:", import.meta.env);

Make sure that you have defined a variable in the desired deployment via Railway UI: https://docs.railway.com/guides/variables#service-variables


clashing

Just try this:const TELEGRAM_BOT_TOKEN = import.meta.env.VITE_TELEGRAM_BOT_TOKEN; console.log("Token is", TELEGRAM_BOT_TOKEN); console.log("Env:", import.meta.env);Make sure that you have defined a variable in the desired deployment via Railway UI: https://docs.railway.com/guides/variables#service-variables

killhead
PROOP

4 months ago

there is no difference with what I'm doing now and it is not working

though, I checked container env and it contains environment variable. So, it's not really Railway to blame, but VITE that doesn't read existing env variable


killhead

there is no difference with what I'm doing now and it is not workingthough, I checked container env and it contains environment variable. So, it's not really Railway to blame, but VITE that doesn't read existing env variable

clashing
FREE

4 months ago

Mine was not accessing the window object, as it poses some issues while accessing that!

Nonetheless, what is being printed when you do console.log("Env:", import.meta.env)? Just to be sure, you have replaced the token with your actual one, because the templates do have an empty field for the env (as they need to be filled by the users; in-case you are using a template)


Status changed to Open brody • 4 months ago


Loading...