Environment variable unavailable during build
neall
PROOP

10 months ago

Issue

Unable to access environment variables during build phase. This is only happening in one service, so I'm certainly doing something wrong.

Context

I have a Node.js / TS application, using this build command:pnpm turbo run build --filter=@org/my-app

// package.json

  "scripts": {
    "check-env": "tsx src/env.ts",
    "build": "pnpm run check-env && tsc",
}

I do the above to force build failure (`env.ts` will throw if needed), so I don't have missing variables at runtime.

// src/env.ts

import "dotenv/config";

const requiredEnvVars = [
  "MAILGUN_API_KEY",
  "PORT"
] as const;

type EnvVars = {
  [key in (typeof requiredEnvVars)[number]]: string;
};

const env = {} as EnvVars;

for (const key of requiredEnvVars) {
  const value = process.env[key];
  if (!value) {
    throw new Error(`Missing required environment variable: ${key}`);
  }
  env[key] = value;
}

console.log("Environment variables loaded successfully");

export default env;

The above file throws the error that fails the build. I'm unsure why the environment variables wouldn't be present, as they're set correctly on the project. Everything works fine at runtime if I don't check during build.

What might be going wrong? And a more general question: is there a better pattern than what I'm doing to catch missing vars, etc. quickly?

Thanks!!

Solved

3 Replies

brody
EMPLOYEE

10 months ago


Status changed to Awaiting User Response Railway 10 months ago


neall
PROOP

10 months ago

Amazing - fixed. Thank you Brody!!


Status changed to Awaiting Railway Response Railway 10 months ago


brody
EMPLOYEE

10 months ago

Awsome!


Status changed to Awaiting User Response Railway 10 months ago


Status changed to Solved brody 10 months ago


Loading...