Cannot access env from Railway to Nestjs Application
khadoan209
FREEOP

10 months ago

Currently I'm on Monorepo and hosting api at apps/api

Here is the process of reading ENV, should reading .env file on local only, else reading from railway env

import { config } from 'dotenv';


if (process.env.NODE_ENV !== 'production') {
    console.log('Loading .env file', process.env.NODE_ENV);
    config({
        debug: process.env.DEBUG_ENABLE !== 'production',
    })
} else {
    console.log('Producing .env, skipping loading .env file');
}

Here the outout


> eccho@ start:prod /app

> turbo run start:prod "--filter" "api"

• Packages in scope: api

• Running start:prod in 1 packages

• Remote caching disabled

api:start:prod: cache bypass, force executing e4be23aaf53390a4

api:start:prod: 

api:start:prod: > api@7.4.0 start:prod /app/apps/api

api:start:prod: > node dist/main

api:start:prod: 

api:start:prod: Loading .env file undefined

api:start:prod: [dotenv@16.5.0][DEBUG] No encoding is specified. UTF-8 is used by default

api:start:prod: [dotenv@16.5.0][DEBUG] Failed to load /app/apps/api/.env ENOENT: no such file or directory, open '/app/apps/api/.env'

api:start:prod: /app/apps/api/dist/app/validate-util.ts.js:21

I use railway dashboard to set .env as NODE_ENV=production

$10 Bounty

3 Replies

10 months ago

You don't need to do all that, dotenv fails quietly when there is no .env file so you only need to have the following

```js
import "dotenv/config";
```

if you need to have the logs though then make sure you deployed the changes made after adding the service variables


dev

You don't need to do all that, dotenv fails quietly when there is no .env file so you only need to have the following```jsimport "dotenv/config";```if you need to have the logs though then make sure you deployed the changes made after adding the service variables

khadoan209
FREEOP

10 months ago

Actually, i test that, but still cannot get environment. I thought dotenv/config cannot ready the .env so it overrides the railways env and delete all current env settings.
Maybe because i use monorepo?


khadoan209
FREEOP

10 months ago

Yes, i am using turbo repo to build and run api

pnpm run build --filter api
pnpm run start:prod --filter api

If you want to pass the global env to current build task, you need to add --env-mode=loose or declear at turbo.json

Ref: Using environment variables | Turborepo


Status changed to Open chandrika 10 months ago


Loading...