recent
🔥 𝐇𝐨𝐭

n8n OpenRouter Integration: API Key, AI Agent & Free Models

Home

n8n OpenRouter Integration: How to Use OpenRouter With n8n in 2026

n8n OpenRouter integration diagram showing API key setup, AI Agent workflow, free model routing, webhook automation, and OpenRouter model connections.

This guide shows how to connect OpenRouter to n8n using the current native OpenRouter Chat Model, secure credentials, and a practical classification-and-routing workflow that keeps working after the AI responds. You'll pass real webhook data into a Basic LLM Chain, turn the result into predictable fields, and route it with a Switch node — then cover the HTTP Request alternative, AI Agent compatibility, free routes, and troubleshooting.

Quick Answer: How to Connect OpenRouter to n8n

Add a Basic LLM Chain (or an AI Agent when you actually need tools), then attach the official OpenRouter Chat Model to its model connector and select a saved OpenRouter credential. Pass dynamic data into the root AI node from an earlier node such as Edit Fields. For direct API control, use n8n's HTTP Request node with a Header Auth credential and send a POST request to https://openrouter.ai/api/v1/chat/completions. The native model node is the simplest starting point; HTTP Request is better when you need full control over the request body.

What You Need Before Connecting OpenRouter to n8n

  • An n8n Cloud account or a self-hosted n8n instance
  • An OpenRouter account and an active API key
  • Basic familiarity with adding and connecting nodes in the n8n editor
  • A currently available OpenRouter model ID (model availability and IDs change, so check the OpenRouter models page before publishing a workflow)

Eligible OpenRouter free routes can be used for testing and low-volume experimentation, so paid credits are not required for the basic workflow. Free-model availability and account-wide limits still apply.

n8n OpenRouter Integration Methods

You'll encounter four OpenRouter to n8n approaches. For a new workflow in 2026, the native OpenRouter Chat Model and the generic HTTP Request node are the two sensible starting points; the other paths mainly matter for legacy or specialized setups.

n8n OpenRouter integration methods
Method Status Best For AI Agent Control Free Routes Main Limitation
OpenRouter Chat Model Official Chains and Agents, fastest setup Yes, model-dependent Managed by the node Yes Behavior varies by n8n version and selected model
HTTP Request Official (generic node) Direct API control, debugging, custom parameters Not as a model sub-node Full — you write the request body Yes You handle parsing, headers, and errors manually
OpenAI Chat Model + Base URL (legacy) Legacy path for n8n before v1.78 Older workflows built before the native node existed Version-dependent Manual Base URL override Version-dependent Legacy compatibility path; prefer the native node for new workflows
Community node Community, third-party package Self-hosted experimentation Unknown, package-specific Package-specific Unknown Maintenance, security, and compatibility risk — not official

Step 1: Get an OpenRouter API Key

Sign in to OpenRouter and generate an API key. OpenRouter authenticates API requests with Bearer tokens; see the official OpenRouter authentication documentation. Copy the key and store it immediately — you'll place it in an n8n credential in the next step, not in a prompt or request body.

Step 2: Add OpenRouter Credentials to n8n

For the native node, create and save the official OpenRouter credential in n8n, then select it in the OpenRouter Chat Model sub-node. Keep the API key inside n8n's credential store rather than repeating it across workflow nodes.

For HTTP Request, use n8n's generic Header Auth credential type instead:

  • Header name: Authorization
  • Header value: Bearer YOUR_OPENROUTER_API_KEY

Select the saved credential in the HTTP Request node's Authentication settings. Never paste the raw key into the request body, a prompt, an expression, a screenshot, or a shared workflow export.

Step 3: Build the n8n OpenRouter Workflow

n8n OpenRouter workflow showing Webhook, Edit Fields, Basic LLM Chain with OpenRouter Chat Model and Structured Output Parser, Switch routing, and automated actions.

The example below classifies an incoming item — a support message, lead, or content brief — into a predictable JSON shape, then routes it based on that classification. It's a more useful starting point than a single prompt-and-response test because it shows a full loop: real input in, structured decision out, automation action after. For more reusable patterns, see 17 n8n workflow examples.

Webhook → Edit Fields → Basic LLM Chain → Switch → Action ↪ OpenRouter Chat Model ↪ Structured Output Parser

Important: OpenRouter Chat Model and Structured Output Parser are not separate steps in a straight line — they're AI sub-nodes that plug into the Basic LLM Chain's model and output-parser inputs. Drawing this as a flat sequence (Chain → Model → Parser → Switch) misrepresents how n8n's AI architecture actually connects.

Example incoming payload:

{ "text": "A customer is blocked from exporting their report.", "source": "website-form" }

Webhook

The Webhook node receives the real payload above as a POST request. Document which fields you expect (text, source) so later nodes can reference them reliably. Don't spend configuration time here beyond setting the path and method — the interesting work happens downstream.

Edit Fields

Use Edit Fields to normalize the incoming data before it reaches the AI nodes. Map the webhook's text field to a stable field name like input_text, and optionally carry over source and a received timestamp. Normalizing here means every later expression references one predictable field name instead of guessing at the raw webhook shape.

Common mistake: assuming the incoming field is already called input_text and skipping this step, which breaks the moment the source payload's field names change.

Basic LLM Chain

Basic LLM Chain is the root AI node for this workflow. It's the right choice here because the job is deterministic classification, not autonomous tool use — the model reads one item and returns one structured answer. Give it a prompt that references the normalized field:

{{ $json.input_text }}

or, referencing a specific earlier node by name:

{{ $('Edit Fields').item.json.input_text }}

Match these names to your actual node names and field names — an expression referencing a renamed node will fail. Connect the OpenRouter Chat Model and Structured Output Parser sub-nodes to this node's model and output-parser inputs, and enable Require Specific Output Format so the chain expects the parser's schema.

Common mistake: starting with an AI Agent before a simple Basic LLM Chain is working end to end. Get the chain producing valid output first.

OpenRouter Chat Model

The official OpenRouter Chat Model sub-node supplies the model to the Basic LLM Chain. Select your saved OpenRouter credential and choose a currently available model in the node's model selector. Before relying on a model, verify its exact ID, context length, modality, and any capabilities your workflow requires. If you use OpenRouter-native tool calling or structured-output parameters, support can vary by model and provider endpoint.

Sub-node expression rule: n8n documents that expressions inside AI sub-nodes always resolve against the first input item, unlike ordinary root nodes that resolve an expression separately for each item. If your workflow processes multiple items, put per-item dynamic mapping in root nodes like Edit Fields and Basic LLM Chain — don't expect a changing expression inside OpenRouter Chat Model to update per item, or every item will silently reuse the first one's value.

Structured Output Parser

The Structured Output Parser is the schema layer your Switch node depends on. In the parser's Schema Type, you can use Generate from JSON Example and provide an object like this (or define an equivalent JSON Schema):

{
  "category": "support",
  "summary": "Customer cannot export a report.",
  "priority": "high"
}

Common mistake: treating JSON-looking prose from the model as validated JSON. A model can return text that looks like JSON without actually matching your schema; the parser is what enforces the exact fields the rest of the workflow depends on. This is separate from OpenRouter's API-level response_format, which is available only on compatible model/provider endpoints.

Switch and Downstream Actions

The Switch node turns the parsed AI output into real branching logic — this is where the workflow stops being a demo and starts being automation. After confirming the parser output path in the execution preview, route on the validated priority or category value:

  • priority = high → Slack or Email alert
  • category = content → Google Sheets
  • priority = low → archive or end

Map only the structured fields each downstream node actually needs — don't forward the entire raw model response into Slack or a spreadsheet when three fields will do.

How to Pass Dynamic n8n Data to OpenRouter

Dynamic data flows through standard n8n expressions. Reference the current item's field directly:

{{ $json.input_text }}

or pull from a specific named node anywhere upstream:

{{ $('Edit Fields').item.json.input_text }}

Both forms work in root nodes like Edit Fields and Basic LLM Chain. Remember the sub-node caveat above: inside OpenRouter Chat Model itself, an expression resolves against the first item only, so per-item dynamic prompts belong in the chain's own prompt field, not buried inside the model sub-node.

How to Reuse OpenRouter Output in the Next Node

After the Basic LLM Chain runs, open the execution output and confirm the exact path where your current n8n node version exposes the parser-produced object. Then map the validated category, summary, and priority values into downstream nodes. This avoids hard-coding a field path that can differ across node versions or configurations. Typical patterns:

  • Switch routes on priority or category
  • Slack or Email messages interpolate summary into the alert text
  • Google Sheets appends a row built from the structured fields
  • A further HTTP Request node sends the classification to another system

Resist the urge to pass the entire raw model response forward. Extracting only the fields a downstream node needs keeps messages readable and avoids leaking prompt content into places like Slack channels or spreadsheets where it doesn't belong.

Using OpenRouter With the n8n HTTP Request Node

HTTP Request is the direct-control alternative once the native workflow above is working. It's useful when you need a parameter the native node doesn't expose, want full visibility into the raw request and response, or are integrating OpenRouter outside an AI root node entirely. If you're new to the raw API itself, start with the OpenRouter API guide for beginners. OpenRouter's official quickstart documents the same Chat Completions endpoint used below.

HTTP Request configuration for OpenRouter
Field Value
Method POST
URL https://openrouter.ai/api/v1/chat/completions
Authentication Header Auth credential
Header Authorization: Bearer <credential value>
Additional header Content-Type: application/json
Body type JSON
Streaming false for this basic workflow

Copyable request body:

{ "model": "YOUR_CURRENT_MODEL_ID", "messages": [ { "role": "system", "content": "Classify the incoming item and return only the requested JSON." }, { "role": "user", "content": "{{ $json.input_text }}" } ], "temperature": 0.2, "stream": false }

Leave the model ID as a placeholder until you've confirmed a currently available model in OpenRouter's current catalog — hard-coding a specific ID here would go stale. If the HTTP route must enforce an exact JSON Schema, use OpenRouter's structured-output API only with a compatible model/provider endpoint; don't assume every route supports response_format.

HTTP Response Extraction

For a standard non-streaming Chat Completions response, the generated text sits at:

{{ $json.choices[0].message.content }}

This applies to the HTTP Request route specifically. The native OpenRouter Chat Model node returns its output in the shape the connected AI root node expects, not necessarily this same raw structure — treat the two paths' outputs separately when building expressions.

How to Use OpenRouter With the n8n AI Agent

Yes — OpenRouter can power an n8n AI Agent through the official OpenRouter Chat Model node, but practical compatibility depends on the selected model/provider supporting the features the Agent needs, especially tool calling.

Webhook or Chat Trigger → AI Agent → Response or action ↪ OpenRouter Chat Model ↪ Tool(s)

Connect OpenRouter Chat Model to the Agent's model input exactly as you would for a chain. What changes is the requirement: the model/provider combination you select must support tool calling for the Agent to actually decide and invoke tools, and structured output support is a separate capability — a model can support one without the other. Some free models or routes support tools, but support and availability are model/provider-dependent, so verify the exact route before building an Agent around it. Use the Agent's current Max Iterations setting to keep tool loops bounded, and validate each connected tool independently.

Basic LLM Chain vs AI Agent

Use Basic LLM Chain when input flows through the model into a predictable structured response — classification, extraction, summarization, deterministic routing. Use AI Agent when the model itself needs to choose which tool to call, in what order, based on the input it receives. The classification-and-routing workflow in this article is a chain problem, not an agent problem, which is why it's built around Basic LLM Chain rather than AI Agent.

How to Use Free OpenRouter Models in n8n

OpenRouter offers two free-access patterns, and they behave differently.

Fixed route — pin a specific free model by ID:

provider/model:free

Use this when you want a known, consistent model identity across runs.

Dynamic route — let OpenRouter pick for you:

openrouter/free

This is a router, not a single model. According to OpenRouter's Free Models Router documentation, it filters the currently available free pool for requested capabilities and then selects an eligible model. If a free route you want isn't exposed in the native n8n model selector, use the HTTP Request method and set the exact model value there.

A few caveats worth keeping in mind:

  • Free model availability changes, and a specific model can become temporarily unavailable
  • openrouter/free can route to a different underlying model between requests, which changes behavior run to run
  • Free usage counts against account-wide rate limits, and those limits differ depending on whether you've ever purchased credits
  • Not every free model supports tools or strict structured output — check the specific model before depending on either
  • Free models can have higher latency during peak usage
  • An explicit model fallback can move the request to a paid model if a paid model ID is included in the fallback list

Free describes price, not privacy. Using a free route doesn't make a request more confidential — evaluate a provider's data-handling policy separately from cost, especially before sending customer data through a free model.

For detailed model selection, see our best free OpenRouter models for programming rather than turning this integration guide into another model-ranking page. For current free-model quotas, check OpenRouter's official rate-limit documentation.

Does n8n Have an OpenRouter Node?

Yes. Current n8n includes an official OpenRouter Chat Model node with its own dedicated OpenRouter credential type, usable in both AI chains and AI Agents. The generic HTTP Request node is the official path for direct OpenRouter API calls and custom request fields outside an AI root node. Third-party community packages that wrap OpenRouter are separate, independently maintained packages and shouldn't be described as official — they carry their own maintenance and compatibility risk. An older setup using the OpenAI Chat Model node with a manually overridden Base URL still works in some installs and is documented by n8n as the path for versions before the native node existed, but it isn't the recommended starting point in 2026.

Common n8n OpenRouter Errors and Fixes

Common n8n + OpenRouter errors and fixes
Symptom Likely Cause n8n Check OpenRouter Check Fix
401 Unauthorized Wrong credential or missing Bearer prefix Credential type and active workflow credential Key status and permissions Recreate or reselect the correct credential
402 Payment Required Insufficient account/API-key credits or a key spending limit Confirm the selected model/route and credential Account balance and per-key limit Add credits or adjust the key limit; if using free models, confirm the current free allowance
429 Too Many Requests n8n concurrency, free-tier limit, or provider capacity Retry settings and execution frequency Rate-limit response and account usage Wait, reduce concurrency, add a bounded retry
Model not found Stale or malformed model ID Model field or expression Current models list Copy the exact current model ID
Provider unavailable Provider outage or restriction Execution error and fallback branch Provider status and routing Let provider routing fail over where eligible, or change provider/model deliberately
Timeout Large context, slow provider, or low node timeout Node timeout and payload size Provider response time and capacity Reduce input size, raise timeout moderately, retry once
Malformed JSON Weak or unsupported structured-output behavior Parser settings and raw output Model's structured-output support Switch to a compatible model and validate output
Expression error Wrong field or node reference Preview the expression against input JSON Not applicable Normalize fields and correct the reference
Bad request Invalid JSON or unsupported parameter Body mode and JSON syntax Supported parameters for the model Remove the unsupported field and validate the body
Context-limit failure Prompt plus output exceeds model context Input size and max tokens Model's context length Truncate input or choose a larger-context model
Agent tool error No tool support or incompatible schema Agent connection and tool definition Model/provider tools support Choose a tool-capable model and bound iterations

Understanding 429 Errors

Don't treat every 429 as "wait a minute and retry." It can come from OpenRouter account limits, free-route-specific limits, a particular model or provider's capacity, or n8n itself sending too many items in parallel. Check both sides: your execution frequency/concurrency in n8n and the error metadata plus account usage in OpenRouter. OpenRouter documents that a 429 can originate from platform limits or an upstream provider/capacity condition; see the current limits page for the live thresholds.

n8n OpenRouter troubleshooting flowchart showing how to diagnose authentication errors, credit issues, 429 rate limits, model errors, timeouts, retries, fallbacks, and error workflows.

Retries, Error Workflows, and OpenRouter Fallbacks

Bounded Retries

For nodes that expose it, n8n supports Retry On Fail. Keep the attempt count small and use the available wait-between-tries/backoff controls for transient failures; after the final attempt, let the workflow fail into your configured error workflow. Don't build an unbounded retry loop, and don't blindly retry errors that a retry can't fix — a wrong API key, a malformed body, or a stale model ID will fail identically every time. Reserve retries for genuinely transient problems: 429s, timeouts, and temporary provider unavailability.

Error Workflow

Don't place an Error Trigger as the last node in your main workflow — that's not how n8n's error handling is designed to work. Instead, build a separate workflow that starts with Error Trigger, containing whatever alerting or logging you want (Slack message, email, log entry), and then point your main workflow's Error Workflow setting at that separate workflow. This is the pattern documented in n8n's error-workflow guide.

Main workflow settings: Error Workflow = "OpenRouter Error Alerts" Separate error workflow: Error Trigger → Slack / Email / Log

OpenRouter Fallbacks vs n8n Retries

These are separate reliability layers. OpenRouter can fail over among eligible providers for the same model according to provider routing, while an explicit model fallback lets a request try another model after an error. An n8n-side retry repeats the node/workflow attempt instead. If you configure model fallbacks, remember that the model ultimately used determines pricing and may have different context, tool, or structured-output capabilities.

How to Keep Your OpenRouter API Key Safe in n8n

  • Use the official OpenRouter credential for the native node, and Header Auth for HTTP Request — enter the raw key only inside the saved credential, never in an ordinary node parameter, prompt, JSON body, or expression
  • Never include a real key in a screenshot, downloadable workflow, or public template; use placeholder credential names in anything you share
  • Workflow exports can contain prompts, sample data, URLs, and headers — review before sharing, and remember execution history can retain sensitive input and output
  • On self-hosted n8n, preserve a stable N8N_ENCRYPTION_KEY, restrict who can access the instance and its execution data, and consider environment-variable or external-secret management for deployment
  • Evaluate a model or provider's data-handling policy independently of price — free describes price, not privacy

Frequently Asked Questions

Is there an official OpenRouter node in n8n?

Yes. The OpenRouter Chat Model node and its dedicated OpenRouter credential are both official, maintained as part of n8n's built-in AI nodes.

Can I use OpenRouter without installing a community node?

Yes. Both the native OpenRouter Chat Model and the generic HTTP Request node work without any third-party package. Community nodes are an option for edge cases, not a requirement.

Why does the native Chat Model work in a chain but fail inside an AI Agent?

Usually because the selected model or provider doesn't support tool calling, which the Agent needs to decide and invoke tools. A Basic LLM Chain doesn't require that capability, so the same model/credential pairing can behave differently depending on which root node it's attached to.

Can a free OpenRouter model return structured JSON?

Yes, but distinguish two layers. n8n's Structured Output Parser can validate the shape used by the workflow, while OpenRouter's native response_format/JSON Schema support is model- and provider-endpoint-dependent. Check the exact route if you rely on OpenRouter-native structured outputs.

Is openrouter/free better than a fixed :free model?

They serve different needs. A fixed provider/model:free route gives you a consistent, known model identity. openrouter/free is a router that picks from available free models dynamically, which is convenient but means the underlying model can change between requests.

Why does a model work when I test it manually but fail in an active workflow?

Common causes include a different item count triggering the sub-node first-item expression behavior, a concurrency spike hitting a rate limit that a single manual test never reached, or a payload from real data that's larger or differently shaped than your test input.

Can OpenRouter embeddings connect directly to n8n vector stores?

OpenRouter provides a separate embeddings API from its chat completions endpoint. The native OpenRouter Chat Model node is built for chat generation, not embeddings, so direct HTTP Request calls are the practical route unless your current n8n release exposes a compatible embedding sub-node. A full embeddings and RAG workflow is a large enough topic to deserve its own guide rather than a section here.

Does a fallback route cost money?

It can. OpenRouter prices a model-fallback request according to the model that ultimately serves it. If a paid model is in your fallback list, a failed free primary can therefore lead to paid usage. Keep the fallback list constrained if zero-cost routing is a hard requirement.

Should I use HTTP Request for production instead of the native node?

Not necessarily — both are official and production-viable. Choose HTTP Request when you need a request parameter the native node doesn't expose, want full visibility into the raw request and response for debugging, or are calling OpenRouter from outside an AI root node entirely.

Where should I look when the model list in OpenRouter Chat Model is empty?

First confirm that the saved OpenRouter credential is valid and actually selected on the node. Then check that your n8n version includes the current OpenRouter Chat Model and compare against OpenRouter's live model catalog. If the native selector still doesn't expose the route you need, use HTTP Request and set a verified model ID directly.

Final n8n OpenRouter Checklist

  • OpenRouter API key generated and stored only in an n8n credential (OpenRouter credential or Header Auth)
  • OpenRouter Chat Model connected as a sub-node to Basic LLM Chain or AI Agent, not treated as a standalone sequential step
  • A current, verified model ID selected — not a hard-coded example
  • Structured Output Parser configured with the exact fields your Switch node needs
  • Dynamic input mapped in root nodes (Edit Fields, Basic LLM Chain), not relied on inside AI sub-node expressions for multi-item runs
  • Downstream node(s) using only the structured fields they need, not the raw model response
  • Bounded retries for transient errors only; a separate Error Workflow configured for alerting
  • Free-route caveats understood if using :free or openrouter/free in anything beyond testing

How We Verified This Guide

This walkthrough was checked against current n8n OpenRouter Chat Model documentation and OpenRouter's official API documentation on August 13, 2026. Volatile details such as model IDs, free-route availability, limits, and UI labels can change, so recheck those items before deploying a production workflow. This article does not claim that the example workflow was imported and executed hands-on.

X