8

NestJS fetch secrets from AWS Secrets Manager

 1 year ago
source link: https://www.niraj.life/blog/nestjs-fetch-secrets-from-aws-secrets-manager
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Niraj Chauhan

#father#husband#SoftwareCraftsman#foodie#gamer#onepiece#naruto

April 21, 2023

NestJS fetch secrets from AWS Secrets Manager

Often, applications use environmental variables to store secrets or values that vary depending on the system where the application runs. These values are typically not checked into the git repositories, and you may need to set them at runtime. The question then arises as to where to save these values so that they are available to your application at runtime.

Locks

One option is to store them in AWS Secrets Manager and use the AWS SDK to fetch them during runtime. In NestJS, you can easily load these values into the ConfigService.

To begin, ensure that the machine running the NestJS application has the necessary permissions to access the AWS Secrets Manager resource. Then, use the following code to fetch the secret values:

import { SecretsManager } from '@aws-sdk/client-secrets-manager';

export default async (): Promise<Record<string, string>> => {
  const secretsManager = new SecretsManager({});
  try {
    const data = await secretsManager.getSecretValue({ SecretId: 'my-app/secrets' });
    if (data.SecretString) {
      const secret = JSON.parse(data.SecretString);
      return secret as Record<string, string>;
    }
  } catch (err) {
    console.error(err);
  }
  return {};
};

Finally, add the secrets to the ConfigModule within the app.module.ts file:

@Module({
  imports: [ConfigModule.forRoot({ isGlobal: true, load: [secrets] })],
})
export class AppModule {}

With these steps, your application will fetch the secret key value data from AWS Secrets Manager and load it into the ConfigService at runtime.

In conclusion, storing sensitive information like passwords or API keys in environmental variables can be a security risk. AWS Secrets Manager provides a secure and easy-to-use solution for storing and managing such sensitive data. With the help of the AWS SDK and the NestJS ConfigService, it is possible to fetch the secrets from AWS Secrets Manager and load them into your application at runtime. This approach ensures that your sensitive information remains secure while still being easily accessible to your application.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK