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 exampleclaude-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
- In the Admin UI open Virtual Keys (
/ui/api-keys) and click + Create New Key. - Under Key Details, set Key Name to
itinerary-writerand leave Key Type on AI APIs, which includes the/bedrockroutes. - 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. - 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. - 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
-
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" -
Set
endpointto the gateway address followed by/bedrock, with no/v1. The client adds/model/<modelId>/converseand the other paths after it. -
Pass the virtual key as
credentials.accessKeyIdand any text assecretAccessKey. The client signs the request with SigV4, and the gateway reads the key from theCredential=part of the signature header. The virtual key is the credential, the signature itself is not checked. -
Set
requestHandlertonew 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 withProtocol error. -
Set
region, for exampleus-east-1. The client needs one to sign, and the gateway uses the region of the deployment, not this one. -
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
| Feature | How to use it through the gateway | Notes |
|---|---|---|
| Converse streaming | ConverseStreamCommand 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. |
| Invoke | InvokeModelCommand with the model's native body, and InvokeModelWithResponseStreamCommand | See Bedrock Invoke. |
| Tools | toolConfig on ConverseCommand | Handled by the Bedrock model as usual. |
| Images and documents | image and document content blocks with bytes | The model must accept them. |
| Prompt caching | cachePoint blocks | Handled by Bedrock for models that support it. |
| Reasoning | additionalModelRequestFields with the model's reasoning setting | Passed to Bedrock unchanged. |
| Token counting | CountTokensCommand | Served on the same /bedrock route. |
| Bidirectional streaming | InvokeModelWithBidirectionalStreamCommand | Not 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.
| Case | err.$metadata.httpStatusCode | Text the gateway sends | Cause and fix |
|---|---|---|---|
| No key on the request | 401 | Authentication Error, No api key passed in. | credentials did not reach the gateway. Check the client setup. |
| Wrong or deleted key | 401 | Authentication 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 key | 401 | Authentication 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 key | 401 | Authentication 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 model | 403 | The 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 spent | 422 | Budget 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 limit | 429 | Rate 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 Bedrock | 500 | The provider's own message, followed by the model group that failed | Ask 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 /v1 | 404 | Not Found | Set endpoint to https://gateway.example.com/bedrock. |
| Bedrock does not know the model id | 400, ValidationException | AWS's own message | A 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/2 | none | None. NghttpError with the message Protocol error | Add requestHandler: new NodeHttpHandler(). |
| Nothing listens at the address | none | None. connect ECONNREFUSED <address>:<port> | Check the address, port and that the gateway runs. In Docker use host.docker.internal. |
| TLS certificate not trusted | none | None. The error code is UNABLE_TO_GET_ISSUER_CERT_LOCALLY or SELF_SIGNED_CERT_IN_CHAIN | Start Node with NODE_EXTRA_CA_CERTS=/path/to/company-root.pem. |
See the client error reference for the same cases in every SDK.
Troubleshooting
- In your catch block, log
err.name,err.$metadata?.httpStatusCodeanderr.$response?.headers?.["x-spanway-call-id"]. - 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. - If the request is not on Logs, it never reached the gateway.
Protocol errormeans HTTP/2 is still on,ECONNREFUSEDand DNS errors mean the address is wrong, and a TLS code means the certificate is not trusted. - A 401 with a key you know is right usually means the client picked up AWS credentials from the environment. Pass
credentialsexplicitly as in the example. - Read
x-spanway-routing-reasonandx-spanway-attemptsin 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.
Related
- Amazon Bedrock with boto3 for the same steps in Python.
- Bedrock Converse API and Bedrock Invoke API for the request formats.
- Bedrock pass-through for other Bedrock runtime paths.
- Connect any client for base URLs and headers on every API surface.
- Client error reference for every gateway error.