Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Next.js and React

The browser refuses to set a header such as User-Agent or Cookie

ErrorRefused to set unsafe header "User-Agent"

Short answer

Browsers reserve some request headers for themselves, so page code cannot set them. Cookie and Origin are forbidden by the Fetch Standard, and Chrome also drops User-Agent. The request goes out without your value. Remove the header, let the browser attach cookies with credentials, and call API-key services such as OpenAI from your own server.

  • Applies to Chrome, Express 5, Node.js 22
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Find every place that sets a request header in the browser code. The header named in the console message is the one the browser rejected.

    grep -rn "setRequestHeader\|User-Agent\|Cookie" src
  2. 2Match what you see, then jump to its fix

    1. 1The console names a header such as User-Agent, Cookie, Origin or Referer, and the server never sees your valuePage code sets a header the browser ownsFix
    2. 2The same refusal message, naming Cookie, on a call that is meant to send a sessionA Cookie header is written by hand instead of using credentialsFix
    3. 3After the Cookie line is removed, the request fails with a network or CORS error instead, or the cookie is never storedCredentials are on, but the other origin has not agreed to themFix
    4. 4The error appears on a call to an API that needs a secret key, made from front-end codeA server-side API such as OpenAI is called straight from the browserFix

What does the error look like?

  • Refused to set unsafe header "User-Agent"
  • The request reaches the server without the header your code set

Cause 1 of 4

Page code sets a header the browser owns

1Check

The Fetch Standard lists forbidden request headers, among them Cookie, Origin and Referer, so that the browser stays in full control of them. Chrome also drops a User-Agent header from Fetch requests, even though the standard no longer lists it. With XMLHttpRequest the call to setRequestHeader is simply skipped.

grep -rn "headers\|setRequestHeader" src --include=*.js --include=*.ts --include=*.tsx

2Fix

Delete the header from the browser code.

fetch('/api/items', {
  headers: { 'Content-Type': 'application/json' },
});

3Verify

Reload with the console open and repeat the request; the refusal no longer appears.

# browser DevTools > Console, then Network > the request > Request Headers

Confirmed by developer.mozilla.org

Did this fix it?

Cause 2 of 4

A Cookie header is written by hand instead of using credentials

1Check

Cookie is on the forbidden list, so a value set in code is ignored. The browser attaches cookies itself, and by default it does so only for same-origin requests.

grep -rn "Cookie\|withCredentials\|credentials" src

2Fix

Ask the browser to include credentials: the credentials option in fetch, or withCredentials in XMLHttpRequest.

// fetch
const res = await fetch('https://api.example.com/profile', {
  credentials: 'include',
});

// XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/profile');
xhr.withCredentials = true;
xhr.send();

3Verify

In the Network panel, the request now lists a Cookie header added by the browser.

# browser DevTools > Network > the request > Request Headers

Confirmed by developer.mozilla.org

Did this fix it?

Cause 3 of 4

Credentials are on, but the other origin has not agreed to them

1Check

For a cross-origin request with credentials, the server must answer with Access-Control-Allow-Credentials and name the page's origin in Access-Control-Allow-Origin. The wildcard * is not accepted. A cookie marked SameSite Strict or Lax is also not sent cross-site.

curl -i -H "Origin: https://app.example.com" https://api.example.com/profile

2Fix

Set both response headers on the API, with the exact origin of your front end, and review the cookie's SameSite attribute.

Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true

3Verify

Repeat the curl command and look for both headers in the response.

curl -i -H "Origin: https://app.example.com" https://api.example.com/profile | grep -i access-control

Confirmed by developer.mozilla.org

Did this fix it?

Cause 4 of 4

A server-side API such as OpenAI is called straight from the browser

1Check

The OpenAI Node SDK is switched off in browsers by default, because turning it on exposes your secret API key in client-side code. Anyone who opens DevTools can read it.

grep -rn "dangerouslyAllowBrowser\|OPENAI_API_KEY\|apiKey" src

2Fix

Make the call from your own server and let the browser talk only to that endpoint. The browser sends no reserved headers, and the key stays on the server.

// server.js
import express from 'express';
import OpenAI from 'openai';

const app = express();
app.use(express.json());
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

app.post('/api/ask', async (req, res) => {
  const response = await client.responses.create({
    model: 'gpt-5.5', // a model name as used in the SDK README
    input: req.body.question,
  });
  res.json({ answer: response.output_text });
});

app.listen(3000);

// browser
const res = await fetch('/api/ask', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ question }),
});
const { answer } = await res.json();

3Verify

Call your endpoint with curl and read the answer field.

curl -s -X POST http://localhost:3000/api/ask \
  -H "Content-Type: application/json" \
  -d '{"question":"Say hello"}'

Confirmed by raw.githubusercontent.com

Did this fix it?

How do I stop it coming back?

  • Treat every header on the forbidden list as the browser's: Cookie, Origin, Referer and the Sec- and Proxy- prefixes are never yours to set.
  • Keep secret API keys out of front-end bundles. Put a small endpoint between the browser and the provider.
  • Use the credentials option from the first request that needs a session, and test it against the real API origin, not only a same-origin dev proxy.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Web apps

The cors-anywhere.herokuapp.com demo proxy stopped working

Missing required request header. Must specify one of: origin,x-requested-with

The public cors-anywhere.herokuapp.com server is only a demo, is rate limited, and since February 2021 requires an opt-in.

2 causes, each with a fix

Web apps

CORS fails when you open an HTML file straight from disk

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///

A page opened from disk has an opaque origin, so browsers treat every request it makes as cross-origin, and CORS only works over http or https.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.