Skip to main content
RapidDev - Software Development Agency
n8n-tutorial

How to Handle 401 Unauthorized from OpenAI After Rotating Keys in n8n

After rotating your OpenAI API key, n8n workflows fail with 401 Unauthorized because the old key is cached in credentials. Fix this by updating the OpenAI credential in n8n's credential manager, clearing the credential cache by restarting n8n or re-saving the workflow, and verifying the new key works with a test execution before re-enabling production workflows.

What you'll learn

  • Why n8n caches credentials and how the cache works
  • How to properly update OpenAI credentials in n8n's credential manager
  • How to flush credential caches across all cache layers
  • How to set up key rotation procedures that avoid downtime
Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Advanced7 min read15-25 minutesn8n 1.20+, OpenAI API, all OpenAI-compatible nodes (OpenAI, AI Agent, HTTP Request)March 2026RapidDev Engineering Team
TL;DR

After rotating your OpenAI API key, n8n workflows fail with 401 Unauthorized because the old key is cached in credentials. Fix this by updating the OpenAI credential in n8n's credential manager, clearing the credential cache by restarting n8n or re-saving the workflow, and verifying the new key works with a test execution before re-enabling production workflows.

Why 401 Errors Persist After Rotating OpenAI API Keys

When you rotate your OpenAI API key — whether for security reasons, after a suspected leak, or as part of regular key rotation — n8n may continue using the old, revoked key even after you update the credential. This happens because n8n caches credentials in memory and some nodes resolve credentials at workflow activation time rather than execution time. The result is persistent 401 Unauthorized errors that seem impossible to fix. This tutorial covers every place the old key might be cached and how to flush each one.

Prerequisites

  • A running n8n instance (self-hosted or cloud) on version 1.20 or later
  • Admin access to n8n's credential manager
  • The new OpenAI API key from platform.openai.com
  • Access to restart n8n (self-hosted) or re-save workflows (cloud)
  • At least one workflow using OpenAI credentials

Step-by-step guide

1

Verify the 401 error is caused by the old API key

Open the failed execution in n8n's Execution History. Click on the failed node (OpenAI, AI Agent, or HTTP Request). The error panel should show '401 Unauthorized' or 'Incorrect API key provided'. Check the timestamp — if the error started exactly when you rotated the key, it confirms the old key is still being used. Also verify the new key works by testing it directly with curl or the OpenAI Playground before troubleshooting n8n.

typescript
1# Test your new API key directly (outside n8n)
2curl -s -o /dev/null -w "%{http_code}" \
3 -H "Authorization: Bearer sk-your-new-key-here" \
4 -H "Content-Type: application/json" \
5 -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"test"}],"max_tokens":5}' \
6 https://api.openai.com/v1/chat/completions
7# Should return 200

Expected result: The curl test returns 200, confirming the new key is valid. The 401 in n8n is caused by the old cached key.

2

Update the OpenAI credential in n8n's credential manager

Go to the n8n main menu → Credentials. Find the OpenAI credential used by your failing workflows. Click on it to open the editor. Replace the API Key field with your new key. Click Save. Important: do not create a new credential — update the existing one. Creating a new credential requires you to update every node that references the old credential, which is error-prone. Updating in place ensures all nodes pick up the new key automatically once the cache is flushed.

Expected result: The credential is saved with the new API key. However, active workflows may still use the cached old key until the cache is flushed.

3

Flush the credential cache

n8n caches credentials in memory for performance. After updating a credential, you need to flush this cache. The method depends on your deployment: (1) Self-hosted: restart the n8n process. (2) n8n Cloud: deactivate and reactivate each affected workflow. (3) Any deployment: open each affected workflow, make a trivial edit (move a node slightly), and save. Saving triggers a credential re-resolution. For self-hosted Docker deployments, restart the container.

typescript
1# Self-hosted: restart n8n to flush all caches
2# Docker
3docker restart n8n
4
5# Docker Compose
6docker compose restart n8n
7
8# PM2
9pm2 restart n8n
10
11# Systemd
12systemctl restart n8n

Expected result: After restart or workflow re-save, n8n resolves the updated credential with the new API key.

4

Handle HTTP Request nodes with hardcoded keys

If any of your workflows use the HTTP Request node to call OpenAI directly (instead of the built-in OpenAI node), the API key might be hardcoded in the Authorization header as a static value rather than referencing a credential. Search your workflows for HTTP Request nodes pointing to api.openai.com and check if the Authorization header uses a credential reference ({{ $credentials.openAiApi.apiKey }}) or a hardcoded key. Update any hardcoded keys to reference the credential instead, so future rotations only require one update.

typescript
1// Bad: hardcoded key in HTTP Request header
2// Authorization: Bearer sk-old-key-here
3
4// Good: credential reference in HTTP Request header
5// Use Header Auth credential type:
6// Name: Authorization
7// Value: Bearer (set in credential, not in node)

Expected result: All HTTP Request nodes calling OpenAI use credential references instead of hardcoded keys.

5

Verify the fix with a test execution

Before reactivating production workflows, run a manual test execution. Open one of the affected workflows, click 'Test Workflow' or 'Execute Workflow' to trigger a single execution. Check that the OpenAI node returns a successful response (200 OK). Inspect the execution output to confirm the response contains valid data. If the test still shows 401, the cache was not fully flushed — try a full n8n restart.

Expected result: The test execution succeeds with a 200 response from OpenAI, confirming the new key is active.

6

Set up a key rotation procedure to avoid future downtime

Implement a rotation procedure that minimizes downtime: (1) Create the new key in OpenAI before revoking the old one. (2) Update the n8n credential with the new key. (3) Flush the cache (restart or re-save). (4) Test with a manual execution. (5) Only then revoke the old key in OpenAI. This overlapping approach ensures there is never a moment when n8n has no valid key. For automated rotation, use n8n's API to update credentials programmatically.

typescript
1// n8n API: Update credential programmatically
2// POST /api/v1/credentials/{credentialId}
3// Use this in a separate n8n workflow triggered on a schedule
4
5// HTTP Request node configuration:
6// Method: PATCH
7// URL: {{ $env.N8N_BASE_URL }}/api/v1/credentials/{{ $json.credentialId }}
8// Headers:
9// X-N8N-API-KEY: {{ $env.N8N_API_KEY }}
10// Body:
11// {
12// "data": {
13// "apiKey": "{{ $json.newApiKey }}"
14// }
15// }

Expected result: A documented rotation procedure that ensures zero-downtime key rotation for all OpenAI workflows.

Complete working example

api-key-health-check.js
1// Complete Code node: API key health check workflow
2// Schedule this to run daily to detect key issues before they cause outages
3
4const https = require('https');
5
6// List of LLM providers to check
7const providers = [
8 {
9 name: 'OpenAI',
10 url: 'https://api.openai.com/v1/models',
11 headers: {
12 'Authorization': `Bearer ${$env.OPENAI_API_KEY}`
13 }
14 }
15];
16
17const results = [];
18
19for (const provider of providers) {
20 try {
21 // Use n8n's built-in HTTP helper if available
22 // This Code node just validates the key format
23 const key = provider.headers.Authorization?.replace('Bearer ', '') || '';
24
25 const checks = {
26 provider: provider.name,
27 keyPresent: key.length > 0,
28 keyFormat: key.startsWith('sk-') ? 'valid' : 'unexpected_format',
29 keyLength: key.length,
30 lastRotated: null, // Would need external tracking
31 status: key.length > 0 && key.startsWith('sk-') ? 'OK' : 'CHECK_REQUIRED'
32 };
33
34 results.push({ json: checks });
35 } catch (error) {
36 results.push({
37 json: {
38 provider: provider.name,
39 status: 'ERROR',
40 error: error.message
41 }
42 });
43 }
44}
45
46return results;

Common mistakes when handling 401 Unauthorized from OpenAI After Rotating Keys in n8n

Why it's a problem: Revoking the old OpenAI key before updating the n8n credential

How to avoid: Always update the credential first, verify it works, then revoke the old key

Why it's a problem: Creating a new credential instead of updating the existing one

How to avoid: Update the existing credential in-place — this avoids having to update every node reference

Why it's a problem: Forgetting to flush the credential cache after updating the key

How to avoid: Restart n8n (self-hosted) or deactivate/reactivate workflows (cloud) after credential updates

Why it's a problem: Hardcoding the API key in HTTP Request node headers instead of using credential references

How to avoid: Use the OpenAI credential type with 'Predefined Credential Type' in the HTTP Request node

Why it's a problem: Not checking HTTP Request nodes for hardcoded keys during rotation

How to avoid: Search all workflows for api.openai.com URLs and verify they use credential references

Best practices

  • Always create the new API key before revoking the old one to ensure overlap
  • Use n8n's credential manager instead of hardcoding keys in HTTP Request headers
  • Restart n8n or re-save workflows after updating credentials to flush the cache
  • Test with a manual execution after key rotation before reactivating production workflows
  • Set up a scheduled health check workflow that validates API key status daily
  • Document which credentials are used by which workflows in a central location
  • Use n8n's API for programmatic credential updates in automated rotation pipelines
  • Enable error notifications so you are alerted immediately when a 401 error occurs

Still stuck?

Copy one of these prompts to get a personalized, step-by-step explanation.

ChatGPT Prompt

My n8n workflow keeps returning 401 Unauthorized from OpenAI even after I updated the API key in the credential manager. How do I fully flush the credential cache and ensure the new key is used?

n8n Prompt

After rotating my OpenAI API key, all n8n workflows using the OpenAI node fail with 401. I updated the credential but the error persists. How do I flush the cache?

Frequently asked questions

Why does n8n cache credentials in memory?

n8n caches credentials for performance — decrypting credentials from the database on every execution would add latency. The cache is refreshed when n8n restarts, when a workflow is saved, or when a workflow is deactivated and reactivated.

How do I know which workflows use a specific OpenAI credential?

Open the credential in n8n's Credentials page. The bottom of the credential editor shows 'Used by' with a list of workflows that reference this credential. Check each one after rotation.

Can I have multiple OpenAI API keys in n8n for different workflows?

Yes, create separate credentials for each key. This is useful for separating production and development keys, or for using different OpenAI organization accounts with different rate limits.

Does n8n Cloud automatically flush credential caches?

n8n Cloud flushes caches when you save a workflow or deactivate/reactivate it. There is no manual restart option on Cloud, so use the save or deactivate/reactivate method.

How often should I rotate my OpenAI API key?

OpenAI recommends rotating keys every 90 days or immediately after a suspected compromise. For n8n workflows, quarterly rotation is a good practice. Set a recurring reminder and follow the procedure in Step 6.

Can RapidDev help set up automated key rotation for n8n workflows?

Yes, RapidDev can build automated key rotation workflows in n8n that integrate with secret managers like AWS Secrets Manager or HashiCorp Vault, automatically update credentials via the n8n API, and send notifications to confirm successful rotation.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Need help with your project?

Our experts have built 600+ apps and can accelerate your development. Book a free consultation — no strings attached.

Book a free consultation

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.