
How to Connect to OpenRouter API: A Complete Developer Guide
Learn how to integrate OpenRouter API into your applications. This tutorial provides a ready-to-run JavaScript/Node.js example to fetch responses from top LLMs effortlessly.
How to Connect to OpenRouter API: A Complete Developer Guide
Integrating large language models (LLMs) into your applications has never been easier, thanks to unified interfaces like OpenRouter. Instead of dealing with separate API keys and billing systems for OpenAI, Anthropic, or Google, OpenRouter gives you access to dozens of models through a single, OpenAI-compatible API.
In this tutorial, we will walk through the process of setting up and connecting to the OpenRouter API using JavaScript.
Why Use OpenRouter?
Before jumping into the code, here are a few reasons why developers prefer OpenRouter:
- Unified Billing: Pay for exactly what you use across different models with one balance.
- OpenAI-Compatible: You can often swap
api.openai.comwithopenrouter.aiand use existing SDKs. - Model Diversity: Access everything from GPT-4o and Claude 3.5 Sonnet to open-source models like Llama 3 and Mistral.
- Free Models: OpenRouter offers a tier of free-to-use models for development and testing.
Prerequisites
- OpenRouter Account: Create an account at openrouter.ai.
- API Key: Navigate to your dashboard and generate a new API key.
- Node.js: Ensure you have Node.js installed if you want to run this outside the browser.
Code Example: JavaScript Fetch
Here is a ready-to-run, dependency-free example using the native fetch API. You can run this in a Node.js environment (v18+) or directly in a browser context.
// index.js
async function fetchChatCompletion() {
const OPENROUTER_API_KEY = "YOUR_OPENROUTER_API_KEY"; // Replace with your actual key
const YOUR_SITE_URL = "https://yourdomain.com"; // Optional, for OpenRouter rankings
const YOUR_SITE_NAME = "My Awesome App"; // Optional
try {
const response = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": `Bearer ${OPENROUTER_API_KEY}`,
"HTTP-Referer": YOUR_SITE_URL,
"X-Title": YOUR_SITE_NAME,
"Content-Type": "application/json"
},
body: JSON.stringify({
// Specify the model you want to use.
// Example: "anthropic/claude-3.5-sonnet" or "openai/gpt-4o"
"model": "meta-llama/llama-3-8b-instruct:free",
"messages": [
{ "role": "system", "content": "You are a helpful coding assistant." },
{ "role": "user", "content": "Write a quick explanation of HTTP status 200." }
]
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
// The response structure matches OpenAI's API format
console.log("Assistant Reply:", data.choices[0].message.content);
} catch (error) {
console.error("Failed to connect to OpenRouter:", error);
}
}
// Execute the function
fetchChatCompletion();
Running the Code
- Save the snippet above into a file named
index.js. - Replace
"YOUR_OPENROUTER_API_KEY"with your generated key. - Run the script from your terminal:
node index.js
Using the Official OpenAI SDK
Since OpenRouter is compatible with the OpenAI API, you can also use the official openai npm package. This is often preferred for production apps because of built-in type safety and error handling.
First, install the package:
npm install openai
Then, configure the client:
import OpenAI from "openai";
const openai = new OpenAI({
baseURL: "https://openrouter.ai/api/v1",
apiKey: "YOUR_OPENROUTER_API_KEY",
defaultHeaders: {
"HTTP-Referer": "https://yourdomain.com",
"X-Title": "My Awesome App",
}
});
async function main() {
const completion = await openai.chat.completions.create({
model: "anthropic/claude-3.5-sonnet",
messages: [
{ role: "user", "content": "Hello, how are you?" }
],
});
console.log(completion.choices[0].message.content);
}
main();
Conclusion
By swapping just the baseURL and the model string, you've unlocked access to the entire LLM ecosystem. OpenRouter drastically reduces the friction of testing different models for your agentic workflows and standardizes the developer experience.
Happy coding!
Related
Resources

The Best AI Tools for Developers in 2026

How MCP Works: A Complete Guide to Model Context Protocol

TypeScript 7.0: Inside the 10x Faster Native Go Compiler

Mastering AI-Assisted Coding: Practical Workflows for 2026
