AWS Secrets Manager + Nodejs

XD
2 min readJan 5, 2023

--

In this article I will show you how you can efficiently fetch credentials/secrets from AWS secrets manager in you backend application (nodejs)

Before we get started on this, we need to have aws-cli installed and configure secrets to run on our local machine

Let’s get started 🚀

1. Create a new secret in AWS Secret Manager

  • Click on Next then add an awesome Name, which we will later on use in code to access this secret

2. Access stored secret from you nodejs application

  • Now that you have stored secrets in AWS, its time to add utils functions that will fetch this credentials for you
  • Create a new file say config.js and copy/paste code below,
const AWS = require("aws-sdk");

let region = "us-east-1",
secret,
secretName = "MySecretName"; //<-- Secret Name from AWS

const client = new AWS.SecretsManager({
region: region,
});

const getAWSAccessCredentials = async () => {
const data = await client.getSecretValue({ SecretId: secretName }).promise();
if ("SecretString" in data) {
secret = JSON.parse(data.SecretString);

for (const envKey of Object.keys(secret)) {
process.env[envKey] = secret[envKey];
}
}
}

module.exports = {
getAWSAccessCredentials
}

3. Efficiently calling secret manager util function

  • Now that we have utils function in place, we can either import and use this function on every file
  • or, we can only call it once and store everything in the current process which we can later access using process.env.secretKey
  • we can achieve this by using a callback such that our backend application only starts listening to incoming requests when we have received credentials/secrets from AWS
require('./config/secretsManager').getAWSAccessCredentials().then(() => {
app.listen(8000);
})

With all the work done above we are good to run this locally

voilla 🎉

--

--

XD
XD

Written by XD

Code by day, hack the system by night. Navigating the cloud like a neon-lit alleyway. APIs, bugs, and glitches – I fix what the future breaks.

No responses yet