Claude and GPT in Node.js: TypeScript Fixes and FAQ
Calling Claude and GPT from Node.js and TypeScript
Calling an AI model from TypeScript is straightforward; debugging the wrong endpoint, model identifier, or environment variable is less obvious. This guide uses the OpenAI SDK with 59API, a low-cost, pay-as-you-go AI API relay, to show a practical setup and the checks that resolve common failures.
59API provides access to multiple model families through one service, including Claude and GPT. For example, you might evaluate Claude Sonnet 5.5 and GPT-6.1 Sol for your application. Use the exact API identifiers provided by the relay, not guessed slugs derived from these display names.
How do I configure the TypeScript client?
Use a supported Node.js LTS release, such as Node.js 22 or newer. In your project directory, run these commands:
npm init -y
npm install openai
npm install --save-dev typescript tsx @types/node
Create a local .env file containing the following variables, each on its own line. Replace the placeholders with your credentials and a model identifier copied from 59API:
API_KEY=your_59api_key
API_BASE_URL=https://api.59api.com/v1
MODEL_ID=copy_the_exact_api_model_identifier
Check the endpoint prefix: https://api.59api.com is the service base address. The configuration above assumes its OpenAI-compatible route uses /v1. Confirm that prefix in the current dashboard or documentation before making requests. The SDK appends endpoint paths to the baseURL you supply.
Create index.mts with this minimal TypeScript example. The .mts extension makes the module format explicit:
import OpenAI from 'openai'; const apiKey = process.env.API_KEY; const baseURL = process.env.API_BASE_URL; const model = process.env.MODEL_ID; if (!apiKey || !baseURL || !model) { throw new Error('Missing API_KEY, API_BASE_URL, or MODEL_ID'); } const client = new OpenAI({ apiKey, baseURL, timeout: 60_000, maxRetries: 2 }); const result = await client.chat.completions.create({ model, messages: [{ role: 'user', content: 'Explain HTTP caching in three sentences.' }] }); console.log(result.choices[0]?.message.content ?? 'No text content returned');
Run it with: npx tsx --env-file=.env index.mts
Keep .env out of version control. In production, inject credentials through your hosting platform’s secret manager. Never expose the relay key in browser JavaScript.
Why does the request fail?
- 401 authentication error: Confirm that the key belongs to 59API, is active, and contains no accidental whitespace. Check that the running process actually loaded API_KEY; a variable in your terminal is not automatically available in every deployment.
- 404 or model not found: Inspect both the base URL and model identifier. Avoid duplicated paths such as /v1/v1. A model’s marketing name may differ from its request identifier, and availability can depend on your account or route.
- 400 unsupported parameter: Start with only model and messages, as above. Add tools, structured output, sampling controls, or token limits individually. SDK compatibility does not mean every model supports every parameter.
- 429 rate limit: Check the error body for quota, balance, or concurrency details. Honor Retry-After when present and use capped exponential backoff with jitter. The example already enables SDK retries; avoid adding an uncontrolled second retry loop.
- Timeout or 5xx response: Record the timestamp, status, and request ID if available. Retry transient failures cautiously: a timed-out generation may still have consumed billable work.
FAQ: Can I switch Claude and GPT without rewriting everything?
For basic chat requests supported by the relay’s OpenAI-compatible interface, usually yes: change MODEL_ID and keep the surrounding client code. Test response quality, latency, tool behavior, and output limits before switching production traffic. Native provider features may require different payloads or endpoints.
FAQ: Why is the response empty?
Inspect the response shape before assuming the request failed. A message can contain tool calls rather than text. With streaming enabled, consume the returned asynchronous stream instead of reading a completed response object. Log metadata during debugging, but redact secrets and sensitive prompts.
FAQ: Is 59API a practical low-cost option?
59API’s low-cost, pay-as-you-go access makes it useful for comparing providers without separate integrations. It offers native official-quality models without downgrading, plus a referral rebate. Compare current pricing, output length, and retry frequency to measure actual cost per successful task. If that fits your workflow, sign up and begin with a small test budget.
शुरू करने के लिए तैयार?
कुछ ही मिनटों में Claude और GPT जोड़ें, सबसे कम कीमत पर। साइन अप करें और API key पाएं।
मुफ़्त साइन अप