Skip to main content

Amazon Bedrock with the JavaScript SDK

The AWS SDK for JavaScript v3 ships the @aws-sdk/client-bedrock-runtime package, whose BedrockRuntimeClient Node.js apps use to call Amazon Bedrock with ConverseCommand and InvokeModelCommand. Pointed at the Spanway gateway, the same commands reach the Bedrock models the gateway serves while the app authenticates with a Spanway virtual key instead of AWS credentials. The gateway signs the call to AWS with its own role, applies the key's budget and rate limit, and records the cost.

A real-world scenario​

A travel company's Node.js booking service writes itinerary summaries with ConverseCommand on Claude in Bedrock. The service ran with an IAM role that could call every Bedrock model in the account. The admin registers only the approved model on the gateway under the public name claude-sonnet-5-5 and gives the service a virtual key named itinerary-writer limited to that name, with a monthly budget. The team points the client at the gateway, removes the Bedrock permissions from the service role, and every summary now shows on the Logs page with its cost.

Prerequisites​

  • A running gateway and its address, written here as https://gateway.example.com.
  • A Bedrock model registered on the gateway. In Models + Endpoints (/ui/models-and-endpoints) the admin clicks Add Model, picks Amazon Bedrock as the Provider, chooses the model and sets the Public Model Name, for example claude-sonnet-5-5. The public name must point at Amazon Bedrock deployments, because this route forwards the Bedrock request body as it is.
  • Node.js 20 or later and the packages, installed with npm install @aws-sdk/client-bedrock-runtime @smithy/node-http-handler.

Make a key for this app​

  1. In the Admin UI open Virtual Keys (/ui/api-keys) and click + Create New Key.
  2. Under Key Details, set Key Name to itinerary-writer and leave Key Type on AI APIs, which includes the /bedrock routes.
  3. In Models, pick every public name the service calls, for example claude-sonnet-5-5, plus any smaller model it uses for background steps. A Bedrock model id that is not on the list is refused with 403.
  4. Open Optional Settings, set Max Budget (USD) with Reset Budget, for example 300 USD monthly, and Requests per minute Limit (RPM), for example 120. Leave Tags empty unless the gateway has an Enterprise license, because key tags need one and without it the key is not created (Only premium users can add tags to keys). The key name already keeps this tool's spend apart in Usage.
  5. Click Create Key and copy the key. It is shown once.

The same key from the API:

curl -X POST https://gateway.example.com/key/generate \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
-d '{"key_alias": "itinerary-writer", "key_type": "llm_api", "models": ["claude-sonnet-5-5"], "max_budget": 300, "budget_duration": "30d", "rpm_limit": 120}'

Steps​

  1. Check the key and the model names with the OpenAI model list, because the Bedrock control plane is not served.

    curl https://gateway.example.com/v1/models -H "Authorization: Bearer $SPANWAY_API_KEY"
  2. Set endpoint to the gateway address followed by /bedrock, with no /v1. The client adds /model/<modelId>/converse and the other paths after it.

  3. Pass the virtual key as credentials.accessKeyId and any text as secretAccessKey. The client signs the request with SigV4, and the gateway reads the key from the Credential= part of the signature header. The virtual key is the credential, the signature itself is not checked.

  4. Set requestHandler to new NodeHttpHandler(). The Bedrock runtime client speaks HTTP/2 by default and the gateway speaks HTTP/1.1, so without this a direct connection to the gateway fails with Protocol error.

  5. Set region, for example us-east-1. The client needs one to sign, and the gateway uses the region of the deployment, not this one.

  6. Use the public model name as modelId, run the app once and find the request on Logs (/ui/logs).

Configuration​

Save as itinerary.mjs and run it with node itinerary.mjs.

import { BedrockRuntimeClient, ConverseCommand } from "@aws-sdk/client-bedrock-runtime";
import { NodeHttpHandler } from "@smithy/node-http-handler";

const client = new BedrockRuntimeClient({
region: "us-east-1",
endpoint: "https://gateway.example.com/bedrock",
requestHandler: new NodeHttpHandler(),
maxAttempts: 2,
credentials: { accessKeyId: process.env.SPANWAY_API_KEY, secretAccessKey: "not-used" },
});

client.middlewareStack.add(
(next) => async (args) => {
const result = await next(args);
console.log("call id", result.response.headers["x-spanway-call-id"]);
return result;
},
{ step: "deserialize", name: "spanwayCallId" },
);

const response = await client.send(
new ConverseCommand({
modelId: "claude-sonnet-5-5",
messages: [{ role: "user", content: [{ text: "Explain a model group in one sentence." }] }],
inferenceConfig: { maxTokens: 200 },
}),
);
console.log(response.output.message.content[0].text);

The small middleware reads the gateway's response headers, which the SDK does not return on its own. Keep it, or log x-spanway-call-id some other way, so every answer can be found again on Logs.

Expected result​

The script prints the call id and the answer. response.usage holds the token counts. x-spanway-call-id is the id to search for on Logs, x-spanway-model-id names the deployment that answered, and x-spanway-response-cost is the call's cost.

On Logs (/ui/logs), click Filters, pick Key Alias = itinerary-writer and click Apply Filters.

Streaming, tools, images, caching and reasoning​

FeatureHow to use it through the gatewayNotes
Converse streamingConverseStreamCommand and for await (const event of response.stream)The gateway returns the Bedrock event stream, which the SDK decodes as usual over HTTP/1.1.
InvokeInvokeModelCommand with the model's native body, and InvokeModelWithResponseStreamCommandSee Bedrock Invoke.
ToolstoolConfig on ConverseCommandHandled by the Bedrock model as usual.
Images and documentsimage and document content blocks with bytesThe model must accept them.
Prompt cachingcachePoint blocksHandled by Bedrock for models that support it.
ReasoningadditionalModelRequestFields with the model's reasoning settingPassed to Bedrock unchanged.
Token countingCountTokensCommandServed on the same /bedrock route.
Bidirectional streamingInvokeModelWithBidirectionalStreamCommandNot served. It needs HTTP/2, and the gateway's Bedrock route covers Converse, Invoke, their streaming forms and token counting.

The client retries throttling errors and 5xx answers on its own, and the gateway has its own retries and fallbacks. The example sets maxAttempts: 2 so a failing request does not turn into many provider calls.

Errors​

For errors the gateway raises itself, the SDK throws an error whose name is Unknown and whose message is UnknownError, because the gateway answers in the OpenAI shape {"error": {"message": "..."}} and the SDK looks for a Bedrock error type. Read err.$metadata.httpStatusCode for the status and err.$response.headers["x-spanway-call-id"] for the call id, then open the call on Logs for the gateway's text. Errors that AWS itself returns keep the Bedrock shape, so the SDK throws them by name, such as ValidationException or ThrottlingException.

Caseerr.$metadata.httpStatusCodeText the gateway sendsCause and fix
No key on the request401Authentication Error, No api key passed in.credentials did not reach the gateway. Check the client setup.
Wrong or deleted key401Authentication Error, Invalid proxy server token passed. key=<hash>, not found in db.The client signed with real AWS credentials, or the key is wrong. Pass credentials explicitly.
Blocked key401Authentication Error, Key is blocked. Update via `/key/unblock` if you're an admin.Ask the admin to open the key in Virtual Keys and click Unblock Key.
Expired key401Authentication Error - Expired Key. Key Expiry time <time> and current time <time>Ask the admin to extend the key or issue a new one.
The key may not use the model403The requested model '<model>' is not available for this API key, or the model name is invalid.Add the public name to the key in Virtual Keys.
The budget is spent422Budget has been exceeded! Key=<key alias> Current cost: <spend>, Max budget: <max>Wait for the reset or ask for a higher budget.
Over the key or team rate limit429Rate limit exceeded for <scope>: <value>. Limit type: <type>.Slow down or ask for a higher limit.
The public name points at a model that is not on Bedrock500The provider's own message, followed by the model group that failedAsk the admin to point the name at Bedrock, or use the OpenAI or Anthropic SDK for other providers.
Wrong path, no /bedrock or an added /v1404Not FoundSet endpoint to https://gateway.example.com/bedrock.
Bedrock does not know the model id400, ValidationExceptionAWS's own messageA name the gateway does not know is sent to Bedrock as a Bedrock model id. Use a public name from GET /v1/models.
The client still speaks HTTP/2noneNone. NghttpError with the message Protocol errorAdd requestHandler: new NodeHttpHandler().
Nothing listens at the addressnoneNone. connect ECONNREFUSED <address>:<port>Check the address, port and that the gateway runs. In Docker use host.docker.internal.
TLS certificate not trustednoneNone. The error code is UNABLE_TO_GET_ISSUER_CERT_LOCALLY or SELF_SIGNED_CERT_IN_CHAINStart Node with NODE_EXTRA_CA_CERTS=/path/to/company-root.pem.

See the client error reference for the same cases in every SDK.

Troubleshooting​

  1. In your catch block, log err.name, err.$metadata?.httpStatusCode and err.$response?.headers?.["x-spanway-call-id"].
  2. Open Logs (/ui/logs), search for the call id or filter by Key Alias, and open the row. It holds the gateway's full error text, which the SDK does not show, plus the deployment and AWS's answer.
  3. If the request is not on Logs, it never reached the gateway. Protocol error means HTTP/2 is still on, ECONNREFUSED and DNS errors mean the address is wrong, and a TLS code means the certificate is not trusted.
  4. A 401 with a key you know is right usually means the client picked up AWS credentials from the environment. Pass credentials explicitly as in the example.
  5. Read x-spanway-routing-reason and x-spanway-attempts in the middleware to see retries and fallbacks, explained on routing decision headers.

More symptoms are in troubleshooting.

Rotation and removal​

Open the key in Virtual Keys, click Regenerate Key, set a Grace Period such as 24h, and deploy the new key before it ends. From the API this is POST /key/{key}/regenerate with {"grace_period": "24h"}, which needs an Enterprise license. Without one, create a new key, switch the service and delete the old key.

Block Key (POST /key/block) stops the service at once and Unblock Key undoes it. Deleting the key (POST /key/delete with {"keys": ["<key>"]}) is permanent. To take the service off the gateway, remove endpoint and credentials and give the client its AWS role again.