Nestjs not loading environment variables
black-brulee
HOBBYOP

2 months ago

I'm experiencing an issue where environment variables configured in Railway are not accessible when my NestJS application initializes services.

Problem:

My NestJS API service crashes on startup with the error: Missing RESEND_SECRET environment variable (or Missing RESEND_API_KEY environment variable), even though these variables are properly configured in the Railway service variables.

Environment Variables Configured:

  • RESEND_SECRET (or RESEND_API_KEY)

All three variables are set in the service's Variables tab in Railway dashboard, and they show as configured (values are masked with asterisks).

What I've Tried:

  1. Verified variables are set in the correct service (not just shared variables)

  2. Tried accessing via process.env directly in the constructor

  3. Tried accessing via NestJS ConfigService

  4. Tried reading variables at module level vs constructor level

  5. Redeployed the service multiple times after adding/updating variables

Code Context:

The service is a NestJS application in a monorepo structure. The failing code is in ContactService constructor:

constructor() {

const resendSecret = process.env.RESEND_SECRET || process.env.RESEND_API_KEY

if (!resendSecret) {

throw new Error('Missing RESEND_SECRET environment variable')

}

// ... rest of initialization

}

$10 Bounty

1 Replies

domehane
FREE

2 months ago

since you mentioned it's a monorepo, i think the issue might be related to how your build tool handles env vars

if you're using turborepo specifically, try adding this to your root turbo.json:

{
  "globalEnv": ["RESEND_SECRET", "RESEND_API_KEY"]
}

turborepo 2.0+ filters env vars by default in strict mode, so they might not be passed through to your nestjs service even though railway has them.

also worth checking - do your railway deployment logs show the env vars being set at build time? you can check the logs to see if they're actually available when your service starts.

if that doesn't work, could you share what monorepo tool you're using and maybe your app.module.ts setup? might help narrow down the issue


Loading...