---
title: "Invoke Amazon Bedrock from Node.js: step-by-step guide | Daniel Segovia"
description: "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."
url: https://danielsegovia.com/en/tutorials/invoke-amazon-bedrock-nodejs/
lang: en
author: "Daniel Segovia"
published: 2026-11-26T14:14:00.000Z
modified: 2026-11-26T13:16:22.744Z
section: "Tutorials"
---

1.  [Home](https://danielsegovia.com/en/)
2.  [Tutorials](https://danielsegovia.com/en/tutorials/)
3.  Invoke Amazon Bedrock from Node.js: step-by-step guide

# Invoke Amazon Bedrock from Node.js: step-by-step guide

[Tutorials](https://danielsegovia.com/en/tutorials/) New By [Daniel Segovia](https://danielsegovia.com/en/about/) · November 26, 2026 · 6 min read

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.

In this post

1.  [Requirements](#requirements)
2.  [Step 1: Pick the region and check available models](#step-1-pick-the-region-and-check-available-models)
3.  [Step 2: Minimal IAM policy to invoke models](#step-2-minimal-iam-policy-to-invoke-models)
4.  [Step 3: Configure credentials and region](#step-3-configure-credentials-and-region)
5.  [Step 4: Init the project and install Bedrock SDK](#step-4-init-the-project-and-install-bedrock-sdk)
6.  [Step 5: Invoke Amazon Bedrock from Node.js with Converse](#step-5-invoke-amazon-bedrock-from-node-js-with-converse)
7.  [Step 6: Streaming with ConverseStream](#step-6-streaming-with-conversestream)
8.  [Step 7: Handle throttling with backoff and jitter](#step-7-handle-throttling-with-backoff-and-jitter)
9.  [Verify it works](#verify-it-works)
10.  [Common errors and fixes](#common-errors-and-fixes)
11.  [FAQ](#faq)

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:

```bash
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`:

```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:

```json
{
  "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.

```bash
aws configure --profile bedrock-dev
export AWS_PROFILE=bedrock-dev
export AWS_REGION=us-east-1
```

On Windows PowerShell:

```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.

```bash
mkdir bedrock-node && cd bedrock-node
npm init -y
npm i @aws-sdk/client-bedrock-runtime
```

## Step 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:

```javascript
// 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:

```bash
export MODEL_ID=anthropic.claude-3-5-sonnet-20240620-v1:0
node index.js
```

On Windows PowerShell:

```powershell
$env:MODEL_ID = "anthropic.claude-3-5-sonnet-20240620-v1:0"
node index.js
```

## Step 6: Streaming with ConverseStream

For long responses, stream and render as it arrives. Create `stream.js`:

```javascript
// 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:

```javascript
// 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.

```bash
node index.js
```

Expected output (example, don’t copy this):

```text
--- 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-model` in the correct region.
    
-   `ResourceNotFoundException: Model 'X' not found`
    
    Your `MODEL_ID` doesn’t exist in that region or has a different name. List models with AWS CLI and fix the ID or change `AWS_REGION`.
    
-   `UnrecognizedClientException: The security token included in the request is invalid`
    
    Invalid creds or wrong profile. Check `AWS_PROFILE` or `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`. Also check system clock skew.
    
-   `ThrottlingException: Rate exceeded`
    
    Lower 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](https://danielsegovia.com/en/tutorials/create-mcp-server-typescript/).

PS: in production, cap concurrency, add timeouts and fallbacks. Nothing teaches availability like a friendly circuit breaker on a Friday evening.

## Tags

-   [#AWS](https://danielsegovia.com/en/tags/aws/)
-   [#Amazon Bedrock](https://danielsegovia.com/en/tags/amazon-bedrock/)
-   [#Node.js](https://danielsegovia.com/en/tags/node-js/)
-   [#TypeScript](https://danielsegovia.com/en/tags/typescript/)

[See all tags →](https://danielsegovia.com/en/tags/)

## Related posts

-   [How to create a TypeScript Lambda with AWS SAM](https://danielsegovia.com/en/tutorials/create-typescript-lambda-aws-sam/)
    
    How to create a TypeScript Lambda with AWS SAM. Initialize the project, compile with esbuild, test locally, and deploy to AWS in minutes without pain.
    
    5 min read
-   [Create an MCP server in TypeScript: step-by-step guide](https://danielsegovia.com/en/tutorials/create-mcp-server-typescript/)
    
    Learn how to create an MCP server in TypeScript, expose tools and resources with the official SDK, and test it with a compatible client.
    
    6 min read
-   [Install Node.js with nvm and switch versions step by step](https://danielsegovia.com/en/tutorials/install-nodejs-nvm-switch-version/)
    
    Install Node.js with nvm on Linux, macOS, and Windows. I'll show you how to install LTS, set a default version, and use .nvmrc per project.
    
    5 min read

## More categories

-   ### [Tutorials](https://danielsegovia.com/en/tutorials/)
    
    [How to create a TypeScript Lambda with AWS SAM](https://danielsegovia.com/en/tutorials/create-typescript-lambda-aws-sam/)
    
    How to create a TypeScript Lambda with AWS SAM. Initialize the project, compile with esbuild, test locally, and deploy to AWS in minutes without pain.
    
    New 5 min read
    
-   ### [News](https://danielsegovia.com/en/news/)
    
    [Huawei speeds chip design; Nvidia slows ASEAN server flows](https://danielsegovia.com/en/news/huawei-speeds-chip-design-nvidia-slows-asean-servers/)
    
    Huawei pushes its homegrown chip-design stack while Nvidia halts AI server shipments in ASEAN. If you bet on one vendor, map risk and ship a plan B.
    
    New 3 min read
    
-   ### [Artificial Intelligence](https://danielsegovia.com/en/artificial-intelligence/)
    
    [OpenAI/Anthropic lock data; China turns to Google and Meta](https://danielsegovia.com/en/artificial-intelligence/openai-anthropic-lock-data-china-google-meta/)
    
    OpenAI and Anthropic restricted data and Chinese players look to Google and Meta. Time to harden pipelines: clear licenses and a data plan B.
    
    New 3 min read
    
-   ### [Security](https://danielsegovia.com/en/security/)
    
    [GoodGuys phishing mimics brands to steal Google/Okta](https://danielsegovia.com/en/security/goodguys-phishing-google-okta-paid-interviews/)
    
    GoodGuys lures with paid interviews to steal corporate Google/Okta creds. Active since October. Priorities: FIDO MFA, phishing drills, and tight SSO control.
    
    New 3 min read
    
-   ### [Architecture](https://danielsegovia.com/en/architecture/)
    
    [Cloudflare toggle for AI-agent search, and you pay the bill](https://danielsegovia.com/en/architecture/cloudflare-toggle-ai-agent-search-cost-privacy/)
    
    Cloudflare added a toggle for AI agents to search your site. You pay the query bill. Good DX, new risks to budgets and privacy. Add access controls and limits.
    
    New 3 min read
    
-   ### [Business](https://danielsegovia.com/en/business/)
    
    [AI infrastructure spend could hit $1T in 2026: now what](https://danielsegovia.com/en/business/ai-infrastructure-spend-2026-1t/)
    
    AI infra investment could reach $1T in 2026. With a $1.8T funding gap through 2030, it’s time to lock budgets, renegotiate contracts and squeeze unit costs.
    
    New 3 min read

---

Sitio: https://danielsegovia.com/ · Índice para agentes: https://danielsegovia.com/llms.txt · Sitemap: https://danielsegovia.com/sitemap.xml
