Fetching secrets with the AWS SDK v3, parsing JSON secrets, caching so you do not pay per request, handling rotation, the IAM permissions involved, ECS and Lambda alternatives to calling the API, and keeping secret values out of the repo your coding agent works in.

AWS Secrets Manager stores API keys and database passwords encrypted with KMS, and a Node.js app reads them with one SDK call. The trouble starts in production, where a call per request adds latency and cost and a rotated password breaks connections opened with the old one.
This guide covers reading, caching and rotating secrets from Node.js, the ECS and Lambda shortcuts, and an approach where the app never calls the API at all.
Use the modular Secrets Manager client and reuse one client per process. Most secrets are JSON objects, so parse SecretString and check the shape before using it:
// secrets.ts
import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";
const client = new SecretsManagerClient({ region: process.env.AWS_REGION ?? "eu-west-1" });
export interface DbCredentials {
username: string;
password: string;
host: string;
port: number;
}
export async function fetchDbCredentials(secretId: string): Promise<DbCredentials> {
const res = await client.send(new GetSecretValueCommand({ SecretId: secretId }));
if (!res.SecretString) {
throw new Error(`secret ${secretId} has no string value`);
}
const parsed = JSON.parse(res.SecretString) as Partial<DbCredentials>;
if (!parsed.username || !parsed.password || !parsed.host) {
throw new Error(`secret ${secretId} is missing fields`);
}
return { ...parsed, port: Number(parsed.port ?? 5432) } as DbCredentials;
}
The SDK picks up credentials from the default provider chain, which means the ECS task role, the Lambda execution role or your local profile, so the code never contains access keys. That role needs secretsmanager:GetSecretValue on the secret's ARN, and kms:Decrypt on the key if the secret uses a customer managed KMS key rather than the default aws/secretsmanager one.
Secrets Manager charges per secret per month plus a fee per 10,000 API calls, as the pricing page lists, and each call is a network round trip. A service that fetches the database password on every request pays both on every request. Cache the value in memory with a TTL instead, and refetch when the TTL runs out:
// cached-secret.ts
import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";
const client = new SecretsManagerClient({});
const TTL_MS = 5 * 60 * 1000;
const cache = new Map<string, { value: string; fetchedAt: number }>();
const inflight = new Map<string, Promise<string>>();
export async function getSecret(secretId: string, opts: { force?: boolean } = {}): Promise<string> {
const hit = cache.get(secretId);
if (!opts.force && hit && Date.now() - hit.fetchedAt < TTL_MS) {
return hit.value;
}
let pending = inflight.get(secretId);
if (!pending) {
pending = client
.send(new GetSecretValueCommand({ SecretId: secretId }))
.then((res) => {
const value = res.SecretString ?? "";
cache.set(secretId, { value, fetchedAt: Date.now() });
return value;
})
.finally(() => inflight.delete(secretId));
inflight.set(secretId, pending);
}
return pending;
}
The inflight map stops a burst of requests after a cold start from each making its own call. Call getSecret(id, { force: true }) when the downstream system rejects the credentials, so a rotated secret is picked up on the first failure instead of after the TTL.
Rotation writes a new version under the AWSPENDING label, tests it, and then moves AWSCURRENT to it, as the rotation guide describes. Your app reads AWSCURRENT by default, so a short cache picks up the new value, but anything holding connections, such as a Postgres pool, keeps using sessions opened with the old password. For database credentials, prefer a rotation strategy that alternates between two users, so the old password stays valid until the next rotation, and recreate the pool when the cached value changes.
On ECS, the task definition can map a secret to an environment variable with secrets and valueFrom, and ECS resolves it when the task starts, using the task execution role, as the ECS secrets guide explains. The app reads process.env and needs no SDK at all, at the cost that a rotated value only arrives when tasks are replaced.
On Lambda, the Parameters and Secrets extension runs a local cache on localhost:2773 inside the execution environment, which is the managed version of the cache above. Both options move secret handling into infrastructure configuration, which then has to be kept in sync with the code that reads the variables.
Encore brings infrastructure from code, so a secret is a one-line TypeScript declaration that the compiler tracks, and when you deploy to AWS Encore replicates the value into AWS Secrets Manager in your own account and injects it into the service's container at runtime. The service calls the secret as a function and never touches the Secrets Manager API, IAM policies or environment variable names.
Run in your terminal to get started locally.
The billing service declares the payment provider key as a secret and uses it in an outgoing call:
// billing/encore.service.ts
import { Service } from "encore.dev/service";
export default new Service("billing");
// billing/customers.ts
import { api, APIError } from "encore.dev/api";
import { secret } from "encore.dev/config";
// API key for the payment provider, set per environment.
const paymentsApiKey = secret("PaymentsApiKey");
interface CreateCustomerParams {
email: string;
}
interface CreateCustomerResponse {
customerId: string;
}
export const createCustomer = api(
{ expose: true, method: "POST", path: "/billing/customers" },
async ({ email }: CreateCustomerParams): Promise<CreateCustomerResponse> => {
const res = await fetch("https://api.payments.example.com/v1/customers", {
method: "POST",
headers: {
Authorization: `Bearer ${paymentsApiKey()}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ email }),
});
if (!res.ok) {
throw APIError.unavailable(`payment provider returned ${res.status}`);
}
const body = (await res.json()) as { id: string };
return { customerId: body.id };
},
);
Values are set per environment type from the CLI, and a deploy fails if the target environment is missing one:
encore run resolves the local value, so the endpoint works on your laptop against the provider's test mode. On deploy to your AWS account, Encore provisions an IAM role for the service, and the AWS infrastructure docs describe how the service reads its secrets from AWS Secrets Manager at runtime.
The values themselves are never written to the repository or to a .env file, so a coding agent working in the repo can add a new secret declaration and the code that uses it, but the production value is not in the repo or in git. Someone with access sets the value with encore secret set, and the agent's change runs locally with the local value.
Best fit: services on AWS that hold third-party credentials and want them in Secrets Manager in their own account, out of the repo their team and agents work in.
SecretsManagerClient per process and rely on the default credential chain.secretsmanager:GetSecretValue on specific secret ARNs, plus kms:Decrypt for customer managed keys.secrets or the Lambda extension when restart-time or cached values are enough.Install @aws-sdk/client-secrets-manager, create a SecretsManagerClient and send a GetSecretValueCommand with the secret's name or ARN as SecretId. The value is in SecretString, which is often JSON you parse with JSON.parse.
No. Each call adds latency and is billed per 10,000 API calls, so fetch the secret once, cache it in memory with a TTL of a few minutes and refresh it in the background or on an authentication failure.
secretsmanager:GetSecretValue on the secret's ARN, and kms:Decrypt on the KMS key if the secret is encrypted with a customer managed key instead of the default aws/secretsmanager key. Grant them to the role your app runs under, such as the ECS task role or the Lambda execution role.
Read the AWSCURRENT version, cache it with a short TTL, and on an authentication error refetch the secret before failing. During rotation the old and new values can both be valid for a short time, so a short cache plus a retry covers the switch.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.