# 🌐 Using OpenRouter Free & Paid Models with Node.js

If you’re just gett[ing starte](https://openrouter.ai/)d with **Generative AI** and don’t want to burn through paid API credits, you can experiment with **OpenRouter**. OpenRouter provides access to multiple AI models, including free ones like **DeepSeek Chat v3.1 (free)**.

In this guide, we’l[l cover:](https://openrouter.ai/)

✅ How to set up Ope[nRouter wi](https://openrouter.ai/)th Node.js  
✅ Example code to call a free model  
✅ How to manage your API key  
✅ Limitations & best practices  
✅ How tokens work in **free vs. paid models**

---

## 1️⃣ Get Your OpenRo[uter API K](https://openrouter.ai/)ey

1. Go to [OpenRouter](https://openrouter.ai/).
    
2. [Sign up](https://openrouter.ai/) with your e[mail or Gi](https://openrouter.ai/)tHub/Google account.
    
3. Head to the **API Key**[**s** section.](https://openrouter.ai/)
    
4. Copy your API key a[nd save it](https://openrouter.ai/) in a `.env` file.
    

Example `.env` file:

```bash
OPENAI_API_KEY=your-openrouter-api-key
```

⚠️ Even though it’s [free, kee](https://openrouter.ai/)p your key secret — don’t commit it to GitHub.

---

## 2️⃣ Set Up Your Nod[e.js Proje](https://openrouter.ai/)ct

Install dependencie[s:](https://openrouter.ai/)

```bash
npm install dotenv node-fetch
```

Project structure:

```plaintext
📂 gen-ai
 ┣ 📂 src
 ┃ ┗ index.js
 ┣ .env
 ┣ package.json
```

---

## 3️⃣ Example Code fo[r a Free M](https://openrouter.ai/)odel

Here’s a working **in**[**dex.js** exa](https://openrouter.ai/)mple:

```js
import dotenv from "dotenv"; // Loads environment variables from .env file
import fetch from "node-fetch"; // Imports fetch for making HTTP requests

dotenv.config(); // Initializes dotenv to use environment variables

async function main() {
  // Sends a POST request to OpenRouter's chat completions endpoint
  const response = await fetch(
    "https://openrouter.ai/api/v1/chat/completions",
    {
      method: "POST", // HTTP method
      headers: {
        Authorization: `Bearer ${process.env.OpenAI_API_KEY}`, // Authenticates using API key from .env
        "Content-Type": "application/json", // Specifies JSON payload
        // "HTTP-Referer": "<YOUR_SITE_URL>", // Optional: site URL for OpenRouter rankings
        // "X-Title": "<YOUR_SITE_NAME>", // Optional: site name for OpenRouter rankings
      },
      body: JSON.stringify({
        model: "deepseek/deepseek-chat-v3.1:free", // Specifies the model to use
        messages: [
          //   { role: "system", content: "You are a helpful assistant." }, // Optional system prompt
          //   { role: "user", content: "What is the capital of France?" }, // Example user prompt
        ],
      }),
    }
  );

  // Parses the JSON response from the API
  const completion = await response.json();
  // Logs the assistant's reply to the console
  console.log(completion.choices[0].message.content);
}

main(); // Runs the main function
```

Run the project:

```bash
node src/index.js
```

Output:

```bash
The capital of France is Paris.
```

---

## 4️⃣ Limitations & B[est Practi](https://openrouter.ai/)ces

* **Free models may hav**[**e restrict**](https://openrouter.ai/)**ions** → slower response times, limited requests per day.
    
* **Always check rate l**[**imits** on O](https://openrouter.ai/)penRouter before scaling.
    
* **Prefer paid models** [(like GPT-](https://openrouter.ai/)4, Claude, Gemini) for production apps.
    
* **Structure your code** [→ keep AP](https://openrouter.ai/)I calls in separate utility files for maintainability.
    

---

## 5️⃣ Understanding T[okens (Fre](https://openrouter.ai/)e vs. Paid Models)

OpenAI and OpenRout[er bill ba](https://openrouter.ai/)sed on **tokens**, not words.

👉 A **token** is a chu[nk of text](https://openrouter.ai/) (roughly 4 characters in English).  
Example: `ChatGPT is awesome!` → 4 tokens (`Chat`, `GPT`, `is`, `awesome!`).

## 6️⃣ How to Calculat[e Tokens i](https://openrouter.ai/)n Node.js

Install the token e[ncoder:](https://openrouter.ai/)

```bash
npm install js-tiktoken
```

Example usage:

```js
import { encoding_for_model } from "js-tiktoken";

const encoder = encoding_for_model("gpt-4");

const text = "ChatGPT is amazing!";
const tokens = encoder.encode(text);

console.log("Token count:", tokens.length);
```

Output:

```bash
Token count: 4
```

[👉](https://openrouter.ai/) Always track tok[en usage i](https://openrouter.ai/)n **paid models** to estimate cost and avoid surprises.
