Where in code we should use an ENV variable in Nodejs? How we should inject it?

Arun Rajeevan
1 min readFeb 15, 2024

--

Context:
As a developer, we usually think that ENV variable is something which will be available all the time and we don’t think about where in code we should be using it. Recently I was trying to use AWS SSM — Systems Manager service to inject my ENV variables in to my docker container.

Issue I was facing:
My env variable value was undefined even though it is coming properly from AWS SSM API.

So what was the root cause?

export const S3_CONFIG = {
BUCKET: process.env.s3Bucket || 'some-default-bucket'
}

When my Node js app initializes, it will first load all the files and export all the constants.
Unfortunately, before even my ENV variable value gets set from AWS SSM, my S3_CONFIG file gets imported and the value becomes the ‘some-default-bucket’.

How we should inject it?

export class GetClientFileListHandler implements IHandler {
s3BucketName: string;
constructor() {
this.s3BucketName = process.env.s3Bucket;
}
}

In the above code snippet, the value will only be injected when we create instance of the class GetClientFileListHandler.

--

--

No responses yet