This workspace contains a minimal Node.js example for calling the OpenRouter API.
- Copy
.env.exampleto.env. - Set
OPENROUTER_API_KEYin.env. - Run with Node 18+:
npm install
npm startOr run the axios example:
npm run start:axiosOr run the CLI prompt version:
npm run start:cli "Tell me a short developer welcome message"Or interactively:
npm run start:cliYou can run a local API server that accepts POST requests at /chat.
npm run serve:openrouterOr the TypeScript version:
npm run serve:openrouter:tsThen send a request like:
curl -X POST http://localhost:3000/chat \
-H "Content-Type: application/json" \
-d '{"message":"Hello from the local OpenRouter API"}'The server also exposes a health endpoint:
curl http://localhost:3000/healthA smoke test verifies the local OpenRouter API server starts and responds to /health.
npm testThe CI workflow runs this test with a dummy API key.
You can also run the TypeScript versions directly with ts-node:
npm run start:ts
npm run start:axios:ts
npm run start:cli:ts "Write a short OpenRouter welcome message"To type-check the TypeScript files:
npm run build:ts- Reads
OPENROUTER_API_KEYfrom.envor the environment. - Sends a chat completion request to
https://api.openrouter.ai/v1/chat/completions. - Prints the JSON response.
openrouter-client.jsuses built-infetchavailable in Node 18 and later.openrouter-axios.jsusesaxiosand is configured inpackage.json.- If you need a different model, set
OPENROUTER_MODELin.envor the environment, or updateDEFAULT_MODELinopenrouter.js.
The shared helper in openrouter.js provides:
loadEnv()for.envfallback loadinggetApiKey()for API key validationcreateChatPayload(message)to build request payloadsOPENROUTER_ENDPOINTfor the OpenRouter API URL