a year 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!!
3 Replies
a year ago
Hello,
Since you are using Turbo, perhaps these docs will help -
https://turbo.build/repo/docs/crafting-your-repository/using-environment-variables#environment-modes
Status changed to Awaiting User Response Railway • 12 months ago
Status changed to Awaiting Railway Response Railway • 12 months ago
Status changed to Awaiting User Response Railway • 12 months ago
Status changed to Solved brody • 12 months ago
