n8n credentials and security official
Use when handling any auth, API keys, tokens, OAuth, bearer tokens, basic auth, or secret values in n8n workflows. Triggers on "API key", "token", "bearer", "OAuth", "secret", "auth", "credentials", "Authorization header", "x-api-key", or any node configuration that mentions a third-party service.
By- name:
- n8n-credentials-and-security-official
- description:
- Use when handling any auth, API keys, tokens, OAuth, bearer tokens, basic auth, or secret values in n8n workflows. Triggers on "API key", "token", "bearer", "OAuth", "secret", "auth", "credentials", "Authorization header", "x-api-key", or any node configuration that mentions a third-party service.
n8n Credentials and Security
Non-negotiables
- Secrets via the credential system, never in text fields or SDK code. API keys, bearer tokens, OAuth secrets, passwords: all go through
newCredential()or the node'scredentialsparameter. A Set node hardcoding a token and read via{{$json.token}}is a text field with extra steps. - List credentials, then bind by ID. Call
list_credentials({type})before configuring an auth-needing node. One match: bind via 2-argnewCredential('Label', 'credId')at create time, orsetNodeCredentialop onupdate_workflow. Multiple matches: ask the user which. The one-argnewCredential('Label')is a placeholder; n8n auto-assigns the most recently edited credential of that type and silently picks wrong when the user has multiples. - Credential creation is the user's job, not yours. The n8n MCP doesn't expose credential creation. Tell the user the exact credential type to create in the UI, then reference it by label in your node config. Don't attempt to create credentials programmatically and don't accept secrets in chat to "set up later".
Strong defaults
- Use native credentials when available. Every native node (Slack, Gmail, Postgres, OpenAI, etc.) has a credential type. Don't reach for generic credential types when a native option exists.
- For multi-header or header-plus-query auth shapes, use the
httpCustomAuthcredential type. Seereferences/CUSTOM_CREDENTIALS.md.
The credential system
In n8n, credentials are first-class objects:
- Stored encrypted at rest in the n8n database.
- Referenced by ID from nodes that need them.
- Scoped to projects (Cloud & enterprise) or shared globally (some self-hosted setups).
- Identified by a type slug (googleSheetsOAuth2Api, slackApi, httpHeaderAuth). The slug is what nodes reference and what determines which auth fields the credential collects.
A node that needs auth has a credentials parameter pointing to a credential ID + type. Secret values never appear in workflow JSON. Exporting a workflow leaks the reference, not the secret.
For the full model (SDK resolution, rotation, project scoping), see references/CREDENTIAL_SYSTEM.md.
Decision tree: how to authenticate this thing
Need to call an external service?
├── Native credential exists (Slack, Gmail, OpenAI, Postgres, ...)?
│ └── Use the native node + its credential type. Done.
│
├── Service is "standard-shaped" (REST + Bearer/Basic/OAuth)?
│ ├── Configure HTTP Request with one of the built-in auth types:
│ │ - Generic OAuth2
│ │ - Header Auth
| | - Bearer Auth (same as header auth but with only field being for actual token)
│ │ - Basic Auth
│ │ - Custom Auth
│ └── See references/HTTP_REQUEST_WITH_AUTH.md
│
└── Service needs multiple static headers, or headers plus query params?
└── Use the httpCustomAuth credential type.
See references/CUSTOM_CREDENTIALS.md
When the user pastes a secret into a chat
This happens. The user types something like:
"Set up a workflow to call Acme API with bearer
sk-abc123def456"
What to do:
- Don't put the token in a text field, even temporarily. A Set node that hardcodes the value and is referenced via
{{$json.token}}is a text field with extra steps. - Bind to an existing credential if possible.
list_credentials({type})first; if a match exists, bind viasetNodeCredentialand tell the user which one you used. If none exists, tell them to create one in the UI (Bearer Auth for bearer tokens, Header Auth for custom headers, etc.). Credential creation is still UI-only. - Treat the pasted secret as compromised, and tell the user to rotate it. Don't soften this. The token has been transmitted to the LLM provider, may persist in chat history, transcripts, and cache layers. Tell them: "Rotate this token as soon as the new credential is set up. Treat it as leaked."
When no native node exists
Common case: the user wants a service n8n has no node for. Use HTTP Request with appropriate auth.
references/FINDING_API_DOCS.md: discovering auth scheme, base URL, common shapes.references/HTTP_REQUEST_WITH_AUTH.md: wiring HTTP Request to a credential.references/CUSTOM_CREDENTIALS.md: when built-in auth types don't fit.
Reference files
| File | Read when |
|---|---|
references/CREDENTIAL_SYSTEM.md |
You need to understand how credentials are stored, referenced, scoped, or rotated |
references/CUSTOM_CREDENTIALS.md |
Multi-header / header-plus-query auth in one credential, or per-request signing patterns (HMAC, JWT, webhook validation) |
references/HTTP_REQUEST_WITH_AUTH.md |
Configuring HTTP Request with auth: Bearer, Basic, OAuth, Header Auth |
references/FINDING_API_DOCS.md |
The user mentioned a service you don't have node-level knowledge of |
Anti-patterns
| Anti-pattern | What goes wrong | Fix |
|---|---|---|
Pasting sk-... into HTTP Request's Authorization header value field |
Token in plain text in the workflow JSON, leaks on export, copy, screenshot | Use a credential: Bearer Auth for bearer tokens, Header Auth for other custom auth schemes |
| Storing token in a Set node and referencing via expression | Same problem, value lives in workflow JSON | Same fix: credential, not a Set node |
Storing a secret in $vars.X and reading it as the auth value |
Not encrypted at rest, leaks in exports, no rotation | Use the right credential type (httpBearerAuth, httpHeaderAuth, httpCustomAuth, or the native one). For inbound webhook auth, use the trigger's authentication field, not an IF on $vars.token |
Reaching for $env.X to read a secret during custom auth setup |
Doesn't work, throws at runtime | Use a credential of the appropriate type |
| Using HTTP Request when a native node exists | Loses auto-refresh on OAuth, loses native error handling, more code | Use the native node |
Hardcoding credentials in SDK code (new HttpRequest({ headers: { Authorization: 'Bearer xxx' } })) |
Same leak surface | Use newCredential() in SDK code |
| Asking the user to create a credential without naming the credential type | User picks the wrong type, auth fails confusingly | Always specify: "create a credential of type <exact type name>" |
Open this reference as its own page
How the credential system works
Credentials in n8n are first-class, encrypted, referenced-by-ID objects.
Storage model
- At rest: encrypted in n8n's database with a key derived from
N8N_ENCRYPTION_KEY(self-hosted, managed on Cloud). - In memory: decrypted only when a node executes and needs to authenticate.
- In workflow JSON: never present. The workflow references credentials by
idandname, and secret values are not exported.
The key property: workflow JSON can be safely shared (Git, chat, screenshots) without leaking secrets, as long as you used the credential system instead of pasting values into text fields.
Reference shape
In the workflow JSON, a node that uses credentials has a parameter shaped like:
{
"credentials": {
"<credentialType>": {
"id": "abc123",
"name": "Acme API (prod)"
}
}
}
<credentialType>: the exact internal type string (e.g.,slackApi,googleSheetsOAuth2Api,httpHeaderAuth).id: the credential's UUID in the database.name: the user's display name for the credential.
Both are exported. Neither is sensitive, and knowing the ID does not let an attacker authenticate.
In SDK code
When writing workflow SDK code, reference credentials via newCredential():
const slack = node({
type: 'n8n-nodes-base.slack',
config: {
parameters: { /* ...other params... */ },
credentials: { slackApi: newCredential('Slack') },
},
})
The shape that matters:
- The credential TYPE (
slackApi,gmailOAuth2,httpHeaderAuth, etc.) IS load-bearing. It must match what the node expects. Use the exact n8n type name as shown in the credential picker: "Slack API" and "Slack OAuth2" are different, and "Slack" alone is ambiguous. If the user's request is ambiguous about which auth flavor, ask before guessing. - The string argument to
newCredential('...')is a placeholder label that doesn't bind to a stored credential. At publish time, n8n auto-assigns the most recently edited credential of that type, which silently picks the wrong one when the user has multiples (prod vs staging API keys, two Gmail accounts).
The recommended flow:
- Call
list_credentials({type})to discover what exists. - If exactly one matches, bind by ID. Two paths:
- At create time:
newCredential('Label', 'credId'). The 2-arg form serializes to{ id, name }and hard-binds. - Post-create:
setNodeCredentialop onupdate_workflow:{ type: 'setNodeCredential', nodeName: 'Send Slack', credentialKey: 'slackApi', credentialId: 'abc123', credentialName: 'Slack prod' }
- At create time:
- If multiple match, ask the user which.
- If none, the user creates one in the UI (credential creation is still UI-only), then re-call
list_credentials.
Project scoping
On n8n Cloud and self-hosted with project support:
- Credentials are scoped to projects.
- Project A's workflow can't reference project B's credential without sharing.
- Sharing is opt-in via the UI.
When the user mentions "the prod credential," confirm the project. If multiple projects have similar names, ask before guessing.
Rotation
When a secret value rotates:
- Update the credential in the n8n UI, and the
idstays the same. - Workflows referencing that
idkeep working without redeployment. - This is why credentials are ID-referenced: rotation doesn't break references.
If the user says "I rotated the API key, why is the workflow still failing?", confirm they updated the credential in n8n (not just rotated upstream). Both sides need to match.
Discovery
Use list_credentials({type, query, projectId, ...}) to discover credentials. Returns name, type, scopes, project (never secret values). Pair with setNodeCredential to bind.
Open this reference as its own page
Custom Auth credentials (httpCustomAuth)
The httpCustomAuth credential type covers auth shapes that don't fit n8n's standard built-ins: multiple headers, headers plus query params, or service-specific static values that need to live in the credential rather than the request.
For standard schemes (Bearer, Basic, generic Header Auth, OAuth2), use those built-in types. See HTTP_REQUEST_WITH_AUTH.md. Reach for httpCustomAuth only when a single built-in can't express the shape.
When httpCustomAuth is the right answer
| Auth shape | Type to use |
|---|---|
Authorization: Bearer <token> |
httpBearerAuth (Bearer Auth) |
Authorization: Basic <base64> |
httpBasicAuth (Basic Auth) |
| Standard OAuth2 | oAuth2Api (Generic OAuth2) |
Single custom header (X-API-Key) |
httpHeaderAuth (Header Auth) |
API key in ?api_key=... query string |
httpCustomAuth |
Multiple headers (X-API-Key + X-Tenant-ID) |
httpCustomAuth |
| Header + query combo | httpCustomAuth |
Rule: if the auth values are static and inject as headers or query params, httpCustomAuth works. If the auth value has to be computed per request (HMAC body signing, timestamp + nonce, JWT issuance, inbound webhook validation challenges), compute it with the Crypto node (n8n-nodes-base.crypto) and inject via expression. See n8n-code-nodes-official for the compute side.
Caveat with that workaround: the Crypto node's secret field doesn't bind to a credential, so the signing key has nowhere clean to live. The least-bad pattern is to keep the signing key in an httpCustomAuth credential and have the parent workflow pass it as an input to a sub-workflow that holds the Crypto node, rather than pasting the raw secret into the Crypto node's text field. This is a rough edge of the n8n credential system, not a clean pattern.
Building with httpCustomAuth
Steps:
- In the n8n UI, create a credential of type
Custom Auth(httpCustomAuth). - The credential takes a JSON-shaped configuration:
{ "headers": { "X-API-Key": "abc123", "X-Tenant-ID": "acme-prod" }, "qs": { "version": "v2" } } - The user pastes the secret values into the JSON in the UI, and n8n encrypts the whole credential at rest.
- Reference the credential from HTTP Request in your SDK code.
What gets injected:
headers: each key/value becomes a request header.qs: each key/value becomes a query string parameter.- Consulted per request, no refresh logic (static values).
Asking the user
Give concrete instructions:
"Create a credential in n8n of type
Custom Auth. Paste this JSON, replacing the values:{ "headers": { "X-API-Key": "<your-key>", "X-Tenant-ID": "<your-tenant>" } }Save with name
Acme API (prod)."
Specificity wins. "Make a custom credential" leaves the user picking among options.
Open this reference as its own page
Finding API docs
Before configuring HTTP Request for a non-native service, you need:
- Base URL.
- Auth scheme (Bearer, Basic, Custom Header, OAuth2, signed, etc.).
- Endpoint shape (path, method, body, query params).
- Common error responses for error handling.
Where to look (in order)
- Official API docs. Canonical. Usually
docs.<service>.comordeveloper.<service>.com. - OpenAPI/Swagger spec. Many services publish
openapi.jsonorswagger.json, a complete machine-readable description. - Postman collections. Public workspaces often have working examples with exact headers and body shapes.
- GitHub repos. The service's official SDK reveals the exact auth shape in source.
- The user's existing setup. If they've used the API in another tool (workflow, script, Postman), ask for the snippet. Working code beats generic docs.
What to extract from the docs
For every operation the user wants to perform, record:
Base URL: https://api.acme.com/v1
Auth: Bearer (Authorization header)
OR API key (X-API-Key header)
OR OAuth2 (auth URL: ..., token URL: ..., scopes: ...)
Operation: List widgets
Method: GET
Path: /widgets
Query params: ?limit=N&cursor=X (optional)
Response shape: { data: [...], next_cursor: string }
Common errors: 401 (unauthorized), 429 (rate limit, with Retry-After header)
With this, you configure HTTP Request precisely instead of guessing.
When the docs are bad or missing
Workarounds:
- The web UI uses HTTP under the hood. Open dev tools → Network tab, capture requests, reverse-engineer. Watch out for short-lived session cookies vs. long-lived API tokens, which use different auth schemes.
- Ask the user. Even a
curlcommand from a colleague is useful. - Try it. Fast-feedback iteration (request → error → adjust) beats stalling on incomplete docs. Use
test_workflowto avoid side effects.
Auth scheme detection
A few common signals:
| In docs / examples | Likely auth scheme | n8n credential type |
|---|---|---|
Authorization: Bearer xxx |
Bearer token | Bearer Auth (httpBearerAuth) |
Authorization: Token xxx |
Token (similar to Bearer) | Header Auth (no Token built-in) |
Authorization: Basic xxx |
Basic Auth | Basic Auth |
X-API-Key: xxx |
API key in custom header | Header Auth |
?api_key=xxx |
API key in query string | Query Auth or Custom Auth |
| Two static headers (key + tenant, key + version) | Multi-header auth | httpCustomAuth |
| Auth flow with consent screen | OAuth2 | Generic OAuth2 |
aws-sigv4 |
AWS Signature v4 | Custom, see service-specific docs |
| Two headers (key + signature) | Per-request signing | Crypto node + expression injection. See CUSTOM_CREDENTIALS.md |
| WebSocket upgrade with subprotocol auth | WebSocket auth | Outside HTTP Request scope |
Pagination
Common shapes:
- Cursor:
?cursor=X, response hasnext_cursor. Loop until null/missing. - Page-based:
?page=N&per_page=K, response hastotal_pagesor stop when fewer thanKreturned. - Offset:
?offset=N&limit=K, response hastotalor stop when fewer thanKreturned. - Link header:
Link: <...>; rel="next". Loop until nonextlink.
Note which shape the API uses before writing the workflow. HTTP Request has built-in pagination for all four.
Rate limits
Look for:
- Documented rate (e.g., "100 requests per minute").
- 429 responses with
Retry-Afterheaders. X-RateLimit-Remaining/X-RateLimit-Resetheaders.
Error handling:
- Wire HTTP Request's error output to a Wait node (delay =
Retry-After), loop back. - Or use HTTP Request's
retryOnFailparameter.
One-off scripts can ignore rate limits. Scheduled/production workflows can't.
Sandbox vs. production
Many APIs offer sandboxes with different credentials and base URLs.
- Ask if sandbox credentials are available, since they're safer for development.
- Name credentials clearly (
Acme API (sandbox)vsAcme API (prod)). - Reference the right one per workflow.
Don't develop against production unless explicitly chosen.
What to give back to the user
After research:
"Acme's API uses Bearer auth at
https://api.acme.com/v1. To list widgets,GET /widgetswith optional?limit=N&cursor=X. Cursor-based pagination vianext_cursor. Rate limit: 100 req/min with 429 responses.Create a credential of type
Bearer Authand paste the token in (n8n adds theBearerprefix andAuthorizationheader for you)."
Concrete and specific. The user provides the token, and you wire the rest.
Open this reference as its own page
HTTP Request with auth
When no native node exists, HTTP Request is the right tool. This covers wiring it to a credential cleanly.
For multi-header or header-plus-query auth shapes, see CUSTOM_CREDENTIALS.md.
The pattern
- Create the credential in the n8n UI of the appropriate type.
- In HTTP Request, set
Authentication. Prefer "Predefined Credential Type" if n8n has one for the service (the OAuth flow, refresh, base URL handling are all wired for you). Fall back to "Generic Credential Type" only when no predefined type exists. - Select the credential from the dropdown, or reference it via
newCredential()in SDK code. - Don't put secret values in URL/header text fields. They should reference the credential.
Picking the right auth type
| Service auth | n8n credential type | Notes |
|---|---|---|
Authorization: Bearer <token> |
httpBearerAuth (Bearer Auth) |
Paste the raw token; n8n adds the Bearer prefix and Authorization header automatically |
Authorization: Basic <base64> |
httpBasicAuth (Basic Auth) |
n8n base64-encodes the username:password |
Custom header (X-API-Key) |
httpHeaderAuth (Header Auth) |
Header name: X-API-Key, value: the key |
API key in query string (?api_key=xxx) |
httpQueryAuth (Query Auth) when available, otherwise httpCustomAuth |
|
| Standard OAuth2 | oAuth2Api (Generic OAuth2) |
Configure auth/token URLs and scopes, and n8n handles the flow |
| Multiple headers + query params | httpCustomAuth |
See CUSTOM_CREDENTIALS.md |
| HMAC / per-request signing | No credential type alone | Crypto node + expression injection. See CUSTOM_CREDENTIALS.md and n8n-code-nodes-official |
SDK shape
In SDK code:
// credId from list_credentials({ type: 'httpHeaderAuth' })
const cred = newCredential('Acme API (prod)', '<credId>')
const fetchAcme = node({
type: 'n8n-nodes-base.httpRequest',
config: {
parameters: {
method: 'GET',
url: 'https://api.acme.com/v1/widgets',
authentication: 'genericCredentialType',
genericAuthType: 'httpHeaderAuth',
},
credentials: { httpHeaderAuth: cred },
},
})
Key parameters:
authentication:'predefinedCredentialType'when n8n has one for the service (less setup, refresh handled), otherwise'genericCredentialType'with the matchinggenericAuthType.genericAuthType: credential type string, must match the credential (httpBearerAuth,httpHeaderAuth,httpBasicAuth,oAuth2Api,httpCustomAuth, etc.).credentials: the reference fromnewCredential().
Common mistakes
Token pasted into the URL
// DON'T
url: `https://api.acme.com/v1/widgets?api_key=sk-abc123`
Token now lives in workflow JSON. Fix: credential of type Query Auth or Custom Auth.
Token pasted into a header value field
// DON'T
headerParameters: {
parameters: [
{ name: 'Authorization', value: 'Bearer sk-abc123' }
]
}
Fix: a Bearer Auth credential (or Header Auth for non-bearer schemes) setting the same header. Don't add it to headerParameters.
Mixing headerParameters with credential-injected headers
If the credential injects Authorization (Bearer Auth, Header Auth, or Bearer-style OAuth2), don't also add Authorization in headerParameters. Conflict, undefined behavior.
For multiple headers (e.g., Authorization + X-Tenant-ID), use one httpCustomAuth credential. See CUSTOM_CREDENTIALS.md.
Forgetting to switch authentication from none
The default is often 'none'. Setting genericAuthType and credentials without flipping authentication means the credential is silently ignored. Request goes unauthenticated, API returns 401.
Verify via get_node_types and get_workflow_details that both authentication and credentials are set.
Storing OAuth2 access tokens in a Header Auth credential
oAuth2Api handles the full OAuth2 flow (authorization, token exchange, refresh). Storing access tokens in Header Auth means they expire without refresh, and the workflow starts failing silently.
For OAuth2, use oAuth2Api. Always.
"Just put the key in for now"
Don't. "Fix it later" is the leak path. A credential takes 30 seconds.
If the user explicitly authorizes a one-off (throwaway test workflow):
- Mark
archivedor tagthrowaway. - Tell them to clean up before sharing, exporting, or persisting.
- Don't publish a workflow with inlined secrets. Keep inactive until the credential exists.
Verifying it landed
After create_workflow_from_code or update_workflow, run get_workflow_details and check:
parameters.authenticationis set (not'none').parameters.genericAuthTypematches the credential type.credentials.<type>.idand.namematch the intended credential.- No secret-shaped strings in
parameters: no Bearer prefixes, no token prefixes, no 32+ char random strings outsidecredentialsreferences.
If any fails, auth is misconfigured before the request fires.
More in this playbook
Safe to turn on
Use this skill when an agent or person is about to create, change or enable an automation inside someone else's account or a shared environment: "create this workflow", "build it in the customer's account", "turn it on", "go live", "deploy this automation". Produces a proposal the human approves, an automation created in the off state, and a short list of what only the human can finish.
Workflow buildingMITn8n agents
Design n8n AI agents the right way. Use when building or editing any @n8n/n8n-nodes-langchain.* AI node — an AI Agent, LLM chain, Text Classifier, or Information Extractor — and whenever the user mentions AI agents, LLM with tools, tool calling, $fromAI, system prompts, agent memory, sessionId, structured/JSON output, output parser, RAG, vector store, a chat assistant/bot, or human-in-the-loop review. Covers Agent-vs-chain-vs-classifier choice, the model/memory/tools/outputParser slots, tool names/descriptions as prompt, structured output with autoFix, memory, RAG, human review, and chat topologies.
Workflow buildingMITn8n agents
Design n8n AI agents the right way. Use when building or editing any @n8n/n8n-nodes-langchain.* AI node — an AI Agent, LLM chain, Text Classifier, or Information Extractor — and whenever the user mentions AI agents, LLM with tools, tool calling, $fromAI, system prompts, agent memory, sessionId, structured/JSON output, output parser, RAG, vector store, a chat assistant/bot, or human-in-the-loop review. Covers Agent-vs-chain-vs-classifier choice, the model/memory/tools/outputParser slots, tool names/descriptions as prompt, structured output with autoFix, memory, RAG, human review, and chat topologies.


