Invoke Amazon Bedrock from Node.js: step-by-step guide
Invoke Amazon Bedrock from Node.js using SDK v3. Set up IAM, call the Converse API, and handle throttling so your app doesn’t faceplant under load.
Invoke Amazon Bedrock from Node.js without getting a 429 to the face. I’ll set up minimal IAM, call the runtime’s Converse API with the v3 SDK, and add retries with backoff so throttling doesn’t ruin your day. Copy, paste, ship.
Requirements
- AWS account with Bedrock access in a supported region (for example, us-east-1).
- IAM access to create/attach policies to a user or role.
- Node.js 18 or later.
- AWS CLI optional but handy to profile credentials and list models.
- Model access enabled for at least one text model in that region.
Step 1: Pick the region and check available models
Bedrock support varies by region and model. First decide your region. With AWS CLI, list foundation models that output text:
aws bedrock list-foundation-models --region us-east-1 --query "modelSummaries[?contains(outputModalities, 'TEXT')].{modelId:modelId,provider:providerName}"Tip: if your target model needs access enabled, do that in the Bedrock console. Otherwise you’ll hit AccessDenied.
Step 2: Minimal IAM policy to invoke models
Create a policy like this and attach it to the user or role running Node. Restrict the resource to what you really need. Replace REGION and PROVIDER.MODEL accordingly (e.g., us-east-1 and anthropic.claude-3-5-sonnet-20240620-v1:0).
File bedrock-invoke-policy.json:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel",
"bedrock:InvokeModelWithResponseStream"
],
"Resource": [
"arn:aws:bedrock:REGION::foundation-model/PROVIDER.MODEL"
]
}
]
}For quick tests you can use a wildcard, but don’t ship this to prod:
{
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel",
"bedrock:InvokeModelWithResponseStream"
],
"Resource": "arn:aws:bedrock:REGION::foundation-model/*"
}Step 3: Configure credentials and region
Option A: use an AWS CLI profile and env vars.
aws configure --profile bedrock-dev
export AWS_PROFILE=bedrock-dev
export AWS_REGION=us-east-1On Windows PowerShell:
aws configure --profile bedrock-dev
$env:AWS_PROFILE = "bedrock-dev"
$env:AWS_REGION = "us-east-1"Option B: direct env credentials (for CI). Set AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, optional AWS_SESSION_TOKEN, plus AWS_REGION.
Step 4: Init the project and install Bedrock SDK
Let’s create a minimal project with the Bedrock runtime client.
mkdir bedrock-node && cd bedrock-node
npm init -y
npm i @aws-sdk/client-bedrock-runtimeStep 5: Invoke Amazon Bedrock from Node.js with Converse
Converse normalizes text requests across models. Use an env var MODEL_ID so you’re not hard-coding. Real IDs include anthropic.claude-3-5-sonnet-20240620-v1:0, meta.llama3-1-70b-instruct-v1:0, amazon.titan-text-premier-v1:0.
Create index.js with this content:
// Simple non-streaming Converse invocation
import { BedrockRuntimeClient, ConverseCommand } from "@aws-sdk/client-bedrock-runtime";
const region = process.env.AWS_REGION || "us-east-1";
const modelId = process.env.MODEL_ID; // Define MODEL_ID in your environment
if (!modelId) {
throw new Error("Definí MODEL_ID con el ID del modelo habilitado en Bedrock");
}
// maxAttempts adds client-side retries
const client = new BedrockRuntimeClient({ region, maxAttempts: 5 });
async function main() {
const command = new ConverseCommand({
modelId,
messages: [
{ role: "user", content: [{ text: "Escribí un haiku sobre SRE y café." }] }
],
inferenceConfig: {
temperature: 0.2,
topP: 0.9,
maxTokens: 300
}
});
const res = await client.send(command);
const text = res.output?.message?.content?.map(p => p.text).join("") ?? "";
console.log("\n--- Respuesta ---\n" + text);
}
main().catch(err => { console.error(err); process.exit(1); });Set MODEL_ID and test:
export MODEL_ID=anthropic.claude-3-5-sonnet-20240620-v1:0
node index.jsOn Windows PowerShell:
$env:MODEL_ID = "anthropic.claude-3-5-sonnet-20240620-v1:0"
node index.jsStep 6: Streaming with ConverseStream
For long responses, stream and render as it arrives. Create stream.js:
// Token streaming with ConverseStream
import { BedrockRuntimeClient, ConverseStreamCommand } from "@aws-sdk/client-bedrock-runtime";
const region = process.env.AWS_REGION || "us-east-1";
const modelId = process.env.MODEL_ID;
if (!modelId) throw new Error("Definí MODEL_ID");
const client = new BedrockRuntimeClient({ region, maxAttempts: 5 });
async function main() {
const command = new ConverseStreamCommand({
modelId,
messages: [
{ role: "user", content: [{ text: "Contame, en 5 bullets, prácticas de SRE." }] }
],
inferenceConfig: { temperature: 0.3, maxTokens: 600 }
});
const res = await client.send(command);
process.stdout.write("Streaming: \n");
for await (const event of res.stream) {
if (event.contentBlockDelta) {
const delta = event.contentBlockDelta.delta?.text || "";
process.stdout.write(delta);
}
}
process.stdout.write("\n\n[fin]\n");
}
main().catch(err => { console.error(err); process.exit(1); });Step 7: Handle throttling with backoff and jitter
When you exceed rate limits, Bedrock returns ThrottlingException or 429. The SDK retries, but during spikes add your own backoff with jitter. Here’s a tiny wrapper:
// Exponential backoff + jitter for Throttling/429
import { BedrockRuntimeClient, ConverseCommand } from "@aws-sdk/client-bedrock-runtime";
const client = new BedrockRuntimeClient({ region: process.env.AWS_REGION || "us-east-1", maxAttempts: 3 });
function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
async function sendWithBackoff(command, { base = 200, max = 5000, attempts = 5 } = {}) {
let n = 0;
while (true) {
try {
return await client.send(command);
} catch (err) {
const status = err.$metadata?.httpStatusCode;
const retriable = err.name === "ThrottlingException" || status === 429 || err.name === "ServiceUnavailableException";
if (!retriable || n >= attempts - 1) throw err;
const delay = Math.min(max, Math.round((base * 2 ** n) * (0.5 + Math.random())));
await sleep(delay);
n++;
}
}
}
async function main() {
const command = new ConverseCommand({
modelId: process.env.MODEL_ID,
messages: [{ role: "user", content: [{ text: "Dame 3 ideas para reducir latencia en APIs." }] }]
});
const res = await sendWithBackoff(command);
console.log(res.output?.message?.content?.map(p => p.text).join("") ?? "");
}
main().catch(e => { console.error(e); process.exit(1); });If you also fire multiple requests in parallel, cap concurrency to a sane number. Don’t be the person who sends 100 requests per user and then complains about 429s.
Verify it works
Run the basic script and check that the model returns text.
node index.jsExpected output (example, don’t copy this):
--- Respuesta ---
Guardias de producción,
SRE bebe su café.
Alertas en calma.Common errors and fixes
-
AccessDeniedException: Account is not authorized to use model ...Enable model access in the Bedrock console and ensure your IAM policy includes that
foundation-modelin the correct region. -
ResourceNotFoundException: Model 'X' not foundYour
MODEL_IDdoesn’t exist in that region or has a different name. List models with AWS CLI and fix the ID or changeAWS_REGION. -
UnrecognizedClientException: The security token included in the request is invalidInvalid creds or wrong profile. Check
AWS_PROFILEorAWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY. Also check system clock skew. -
ThrottlingException: Rate exceededLower concurrency, add jittered backoff, and if needed request higher quotas. Meanwhile, cache repeated results.
FAQ
Which model should I pick for Spanish text
Most modern instruction-tuned models handle Spanish well. Try a couple and choose the best trade-off between quality, latency, and cost for your use case.
Can I use TypeScript instead of JavaScript
Absolutely. Install typescript and ts-node, rename files to .ts, and go. SDK typings help a lot with the messages shape.
How do I pass a system prompt or context
Add an initial message with role: "system" and your text. Many models respect that convention in Converse.
How much does Bedrock cost
It depends on the model and tokens. Check pricing in your AWS account and measure real usage. Pro tip: log tokens per request.
If you’re building tools that talk to models and APIs, this guide may help: Create an MCP server in TypeScript.
PS: in production, cap concurrency, add timeouts and fallbacks. Nothing teaches availability like a friendly circuit breaker on a Friday evening.