Google Gen AI JavaScript SDK
The Google Gen AI JavaScript SDK is the @google/genai npm package for Node.js apps and servers that call Gemini with generateContent. Pointed at the Spanway gateway, the app keeps the Gemini request format while the gateway checks a virtual key, applies its budget and rate limit, records the cost and sends the request to the deployment behind the public model name, which can be Gemini on Google AI Studio or Vertex AI, or a model from another provider translated to and from the Gemini format.
A real-world scenario
A web team built a Node.js chat backend for its help center on ai.models.generateContentStream. Marketing wants to try Claude for the same answers without a rewrite. The admin puts the public name help-center-chat in front of a Gemini deployment and later adds a Claude deployment behind the same name. The backend keeps its Gemini code, the gateway translates the request and streams the answer back in the Gemini format, and the team compares cost and quality per model on Usage and Logs.
Prerequisites
- A running gateway and its address, written here as
https://gateway.example.com. - A model registered on the gateway under a public name. This page uses
help-center-chat, a public name in front of a Gemini deployment. - Node.js 22 or later and the SDK, installed with
npm install @google/genai. Run it on a server. A browser would expose the key to every visitor.
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
help-center-chatand leave Key Type on AI APIs. - In Models, pick every public name the backend calls, here
help-center-chat, plus a cheaper model if it summarises conversations in the background. - Open Optional Settings, set Max Budget (USD) with Reset Budget, for example 250 USD monthly, and a Requests per minute Limit (RPM), for example 600. 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": "help-center-chat", "key_type": "llm_api", "models": ["help-center-chat"], "max_budget": 250, "budget_duration": "30d", "rpm_limit": 600}'
Steps
-
Check the key and the model names with the OpenAI model list, because the gateway has no Gemini model list route.
curl https://gateway.example.com/v1/models -H "Authorization: Bearer $SPANWAY_API_KEY" -
Set the base URL to the gateway address without any version and the API version to
v1beta. The SDK builds/<version>/models/<model>:generateContentitself, and the gateway serves thev1betaform. The SDK defaults tov1, which the gateway does not serve forgenerateContent.export GOOGLE_GEMINI_BASE_URL="https://gateway.example.com"export GOOGLE_GENAI_API_VERSION="v1beta"export GEMINI_API_KEY="sk-...your virtual key..."The SDK reads these variables in Node.js only. Make sure
GOOGLE_API_KEYis not also set, because the SDK prefers it overGEMINI_API_KEYand would send that key to the gateway. -
Or pass the values in code with
apiKeyandhttpOptions, as shown below. Values in code win over the environment. -
Use a public model name from step 1 as
model, and find the request on Logs (/ui/logs).
The SDK sends the key in the x-goog-api-key header, which the gateway reads. A base URL that ends in /v1beta makes the SDK call /v1beta/v1beta/..., which fails with 404.
Configuration
Save as chat.mjs and run it with node chat.mjs.
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
apiKey: process.env.GEMINI_API_KEY,
httpOptions: {
baseUrl: "https://gateway.example.com",
apiVersion: "v1beta",
headers: { "x-spanway-tags": "app:help-center-chat" },
},
});
const stream = await ai.models.generateContentStream({
model: "help-center-chat",
contents: "Explain a model group in one sentence.",
});
for await (const chunk of stream) {
if (chunk.text) process.stdout.write(chunk.text);
}
httpOptions.headers sends gateway request headers such as x-spanway-tags, x-spanway-session-id and x-spanway-timeout with every call, see calling the gateway.
Expected result
The script prints the answer as it streams. For a call that does not stream, the response headers are on response.sdkHttpResponse.headers:
const response = await ai.models.generateContent({ model: "help-center-chat", contents: "Hello" });
console.log(response.text, response.sdkHttpResponse?.headers?.["x-spanway-call-id"]);
A run against a test gateway printed this.
A model group is a public name for one or more deployments. c68427f1-9465-42c8-804e-c1fdd4074a82
x-spanway-call-id is the id to search for on Logs. x-spanway-model-group and x-spanway-model-id name the public name and the deployment that answered, and x-spanway-routing-reason says why, see routing decision headers.
On Logs (/ui/logs), click Filters, pick Key Alias = help-center-chat and click Apply Filters.
Streaming, tools, images, caching and reasoning
| Feature | How to use it through the gateway | Notes |
|---|---|---|
| Streaming | ai.models.generateContentStream({...}) and for await. | The SDK calls :streamGenerateContent?alt=sse, served for every model behind the name. The last chunk can carry only usage, so check chunk.text before you print it. |
| Function calling | config: { tools: [{ functionDeclarations: [...] }] } | Translated when another provider answers. |
| Images | { inlineData: { mimeType: "image/png", data: base64 } } parts. | Translated for other providers. The model behind the name must accept images. |
| Structured output | config: { responseMimeType: "application/json", responseSchema: {...} } | Translated for other providers. |
| Context caching | config: { cachedContent: "..." } | It names a cache stored at Google, so use it only with a public name that points at Gemini deployments. |
| Thinking | config: { thinkingConfig: {...} } | Honoured by Gemini deployments. Not translated for other providers. |
| Token counting | ai.models.countTokens({ model, contents }) | Served at :countTokens. |
| Model list | ai.models.list() | Not served, the SDK gets 404. Use GET /v1/models. |
The SDK does not retry unless you set httpOptions.retryOptions, for example { attempts: 3 }, which retries 408, 429 and 5xx answers. The gateway has its own retries and fallbacks.
Errors
Errors the gateway raises come back in the OpenAI shape {"error": {"message": "...", "type": "...", "param": null, "code": "400"}}. The SDK throws ApiError for every 4xx and 5xx answer, with status set to the HTTP status and message set to the whole response body as a JSON string, so parse JSON.parse(err.message).error?.message to get the gateway's text.
| Case | err.status | Text the gateway sends | Cause and fix |
|---|---|---|---|
| No key on the request | 401 | Authentication Error, No api key passed in. | A proxy in between strips x-goog-api-key. Check that hop. |
| Wrong or deleted key | 401 | Authentication Error, Invalid proxy server token passed. key=<hash>, not found in db. | Copy the key again, and check that GOOGLE_API_KEY does not hold a Google key. |
| 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 model to the key in Virtual Keys. |
| The model name is unknown | 400 | Invalid model name passed in model=<name> | The message starts with agenerate_content:. Use a name from GET /v1/models. |
| 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, ask for a higher limit, or set retryOptions. |
The SDK uses API version v1 | 405 | Method Not Allowed | Set apiVersion: "v1beta" or GOOGLE_GENAI_API_VERSION=v1beta. |
Wrong path, often a doubled /v1beta | 404 | Not Found | Use the bare gateway address as baseUrl. ai.models.list() also gets this 404. |
| The provider failed | 500 to 503 | The provider's own message, followed by the model group that failed | Retry later and ask for a fallback deployment. |
| Nothing listens at the address | none | None. A TypeError with the message fetch failed, and err.cause.code is ECONNREFUSED | Check the address, port and that the gateway runs. In Docker use host.docker.internal. |
| TLS certificate not trusted | none | None. fetch failed, with a cause naming 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.status, the parsed gateway message and the time. The response headers are not onApiError, so look the request up by key alias and time. - Open Logs (
/ui/logs), filter by Key Alias and the time range, and open the row for the status, the error, the deployment and the provider's answer. - If the request is not on Logs, it never reached the gateway. A 405 means the API version is still
v1. Afetch failedmeans the address, the port, DNS or TLS is wrong, anderr.causesays which. - For TLS errors,
NODE_EXTRA_CA_CERTSmust be set before Node starts. - Read
x-spanway-routing-reasonandx-spanway-attemptson a successful call to see retries and fallbacks, explained on routing decision headers.
The Google AI Studio pass-through at https://gateway.example.com/gemini forwards every Gemini route to Google unchanged, for apps that need Gemini-only features. 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 in GEMINI_API_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 app and delete the old key.
Block Key (POST /key/block) stops the app at once and Unblock Key undoes it. Deleting the key (POST /key/delete with {"keys": ["<key>"]}) is permanent. To take the app off the gateway, remove baseUrl and GOOGLE_GEMINI_BASE_URL and use a Google API key again.
Related
- Google Gen AI Python SDK for the same steps in Python.
- Google generateContent for every request field the gateway accepts.
- Connect any client for base URLs and headers on every API surface.
- Client error reference for every gateway error.