Environment Variables Not Accessible at Runtime with serve dist
mheland
PROOP

4 months ago

Hi Railway community,

I'm experiencing an issue where environment variables are available during the build process but not accessible at runtime when using serve dist to serve my Vite React application.

Setup:

- Vite React app with TypeScript

- Build command: npm run build (runs tsc && vite build --mode production)

- Start command: npm start (runs serve dist)

- Environment variables are properly set in Railway dashboard

Problem:

- Build process works perfectly and can access VITE_INIT_KEY (confirmed in build logs)

- Runtime fails with "API key is required!" error

- Same code works perfectly with npm start in local development

Build Log (Success):

Added X-Internal-Api-Key header for build-time CDN request

Backend URL fetched: https://backend.redacted.io

✓ built in 13.33s

Runtime Error:

Console Error: Uncaught Error: API key is required!

at ge (index-qy1bqOaY.js:11:202208)

**Vite Configuration:**

I've configured Vite to preserve process.env at runtime for Railway compatibility:

define: {

__BUILD_TIME__: JSON.stringify(new Date().toISOString()),

'process.env': 'process.env'

}

Environment Variable Access:

My code uses a fallback mechanism that tries both import.meta.env and process.env:

export const getEnvVar = (key: string): string | undefined => {

const viteEnvValue = import.meta.env[key];

if (viteEnvValue) return viteEnvValue;

const processEnvValue = process?.env?.[key];

return processEnvValue;

};

Question:

Is there something specific about Railway's static file serving environment (`serve dist`) that prevents access to environment variables at runtime? The variables are clearly available during build but seem to be stripped or inaccessible when the static files are served.

Any insights or Railway-specific configuration recommendations would be greatly appreciated!

Environment:

- Node.js app

- Vite 7.0.2

- serve 14.2.4

- Environment variables confirmed set in Railway dashboard

Solved$10 Bounty

2 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!


mheland
PROOP

4 months ago

OK, we can close this. We are using Usermaven analytics, and when the Usermaven API key was not provided, the app failed with "API Key Missing". It was never a problem with environment variables, it was bad software design, Usermaven should fail 'transparently' - not kill the whole app.tsx, and if the error message had been "Usermaven: API Key Missing" this would have been resolved in 15 seconds.


Status changed to Solved mheland 4 months ago


Loading...