Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 39 ยท Fetch Fundamentals

Headers, Auth and CORS Basics

Learn the Headers class, Accept and Authorization headers, why API keys must not live in front-end code, and how simple and preflighted CORS requests work.

Every HTTP request and response carries headers: small name and value pairs that describe the message. The body holds the data, and the headers say what the data is, who is asking for it and what the receiver is allowed to do with it. Once your requests grow beyond a plain GET, you will set headers on almost every call, to ask for JSON, to prove who you are and to control caching.

This lesson covers the Headers class, the two headers you will use most (Accept and Authorization), what is safe to keep in browser code, and why the browser sometimes blocks a request with a CORS error even though the server answered. If you need a refresher on headers in general, see HTTP for AJAX Developers, and for the fetch() call itself see Your First fetch() Request.

The Headers class

fetch() accepts headers as a plain object, an array of pairs or a Headers object. The Headers class is the most capable of the three. Header names are case-insensitive, and Headers normalizes them to lowercase for you.

JS Working with the Headers class

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice three things in the output. Lookups ignore case. Calling append() twice joins the values into one comma-separated string, because HTTP allows a header to be repeated. And iterating gives the names in lowercase, sorted alphabetically.

Some headers are forbidden: the browser sets them itself and ignores your attempt. Host, Origin, Cookie, Content-Length and anything starting with Sec- are examples. You cannot fake your own Origin, which is exactly why servers can trust it for CORS decisions.

Accept and Content-Type

Two headers describe formats, and people often mix them up:

  • Accept is a request header: "I would like the answer as JSON."
  • Content-Type says what format the body of this message is in. In a request, it describes what you send. In a response, it describes what the server sends back.
JavaScript
const response = await fetch("/api/notes", {
  method: "POST",
  headers: {
    "Accept": "application/json",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ text: "Buy milk" }),
});

When the body is a string, fetch() guesses text/plain;charset=UTF-8, so a JSON body needs an explicit Content-Type. Many servers refuse to parse JSON that arrives labelled as plain text. When the body is a FormData object, do not set Content-Type yourself: the browser adds it together with the multipart boundary that the server needs.

Authorization and bearer tokens

The Authorization header carries credentials. The most common scheme for APIs is a bearer token: a string that proves you were granted access. Whoever bears (holds) the token is trusted, so it must be kept secret.

JavaScript
const response = await fetch("/api/profile", {
  headers: { Authorization: "Bearer " + token },
});

The server checks the token and answers with one of two statuses that are easy to confuse:

  • 401 Unauthorized: "I do not know who you are." The token is missing, expired or invalid.
  • 403 Forbidden: "I know who you are, and you may not do this."

Here is a mock server function that behaves like a real API. It looks at the Authorization header and returns a Response, so you can see both outcomes without a network.

JS A mock API that checks bearer tokens

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first two calls get 401 because the server cannot identify you. The reader's POST gets 403 because the identity is known but lacks permission.

Secrets do not belong in front-end code

Anything that ships to the browser is public. A visitor can open the Network panel or read your bundled JavaScript, so an API key written into your script is visible to everyone who loads the page. Minifying or "hiding" it in a variable changes nothing.

Use this rule of thumb:

  • Public keys designed for the browser (a map tile key restricted to your domain, a publishable payment key) may appear in client code. The provider limits what they can do.
  • Secret keys (database passwords, payment secret keys, keys that cost you money per call) must stay on your server. The browser calls your own endpoint, and your server adds the secret and calls the third party.
sequenceDiagram
    participant B as Browser
    participant S as Your server
    participant P as Paid API
    B->>S: GET /api/weather (no secret)
    S->>P: GET /forecast with secret key
    P-->>S: JSON
    S-->>B: JSON (secret never leaves)

A small proxy endpoint keeps the secret key on the server while the browser only talks to your own site.

User tokens are a different matter, because they belong to the signed-in person. How to store them safely is covered in AJAX Security.

CORS: why the browser blocks a response

Browsers apply the same-origin policy: a script on https://shop.example may not read responses from https://api.other.example unless that server agrees. An origin is the scheme, host and port together. CORS (Cross-Origin Resource Sharing) is the agreement: the server adds headers such as Access-Control-Allow-Origin to say which origins may read its answers.

Two facts clear up most confusion:

  1. The request is usually sent and the server does answer. The browser then refuses to hand the response to your script. A CORS error is a browser decision, not a server crash.
  2. CORS is enforced only by browsers. curl, your server code and mobile apps ignore it, so "it works in Postman" tells you nothing about CORS.

Simple and preflighted requests

For "simple" requests, the browser sends the request straight away and checks the response headers afterwards. A request is simple when it uses GET, HEAD or POST, only safe headers, and for POST a Content-Type of application/x-www-form-urlencoded, multipart/form-data or text/plain.

Anything else, such as a PUT, a custom header or a Content-Type of application/json, triggers a preflight: the browser first sends an OPTIONS request asking "would you accept this?". Only if the server's answer allows the method and headers does the real request follow. Adding an Authorization header also triggers a preflight.

This function is a teaching stand-in that applies those rules, so you can try different requests:

JS Will this request be preflighted?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

sequenceDiagram
    participant B as Browser
    participant S as api.other.example
    B->>S: OPTIONS /items (Origin, requested method and headers)
    S-->>B: 204 with Access-Control-Allow-Origin, -Methods, -Headers
    B->>S: PUT /items (the real request)
    S-->>B: 200 with Access-Control-Allow-Origin

A preflight is an extra OPTIONS round trip that happens before the real request.

The server's answer must include Access-Control-Allow-Origin with your origin (or *) and, for preflights, Access-Control-Allow-Methods and Access-Control-Allow-Headers. If the server never sends these, you see a console message such as "has been blocked by CORS policy". The fix lives on the server (or in a same-origin proxy). Changing your fetch() call cannot fix it. The mode: "no-cors" option does not help either: it only gives you an opaque response whose status and body you cannot read.

By default, fetch() also leaves cookies out of cross-origin requests. To send them you need credentials: "include" and a server that replies with an exact origin (never *) plus Access-Control-Allow-Credentials: true.

Never "fix" CORS by adding a wildcard to a server that handles private data. Access-Control-Allow-Origin: * lets any website read the response. Allow only the origins you trust.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A fetch call to another origin fails with a CORS error in the console. Where is the real fix?

    CORS is the server giving permission. Only the server (or a same-origin proxy you control) can add the headers. The no-cors mode returns an unreadable opaque response.
  2. 2. What does a 401 status mean compared with 403?

    401 means missing or invalid credentials. 403 means the credentials were understood, but the identity lacks permission.
  3. 3. Why should a secret API key not be placed in your JavaScript bundle?

    Anything delivered to the browser is public. Keep secrets on your server and let the browser call your own endpoint.
  4. 4. Which request is preflighted?

    A JSON content type is not one of the three simple types, so the browser sends an OPTIONS preflight first.

Summary

  • Use the Headers class to set, read and loop over headers; names are case-insensitive.
  • Accept states the format you want back; Content-Type labels the body of the message you send.
  • Send bearer tokens in Authorization: Bearer ...; 401 means "who are you?", 403 means "not allowed".
  • Secret keys never ship to the browser; proxy third-party calls through your own server.
  • CORS is permission from the server, enforced by browsers. JSON bodies, custom headers and PUT/DELETE trigger a preflight.

Next, learn to run several requests at once in Async/Await for Requests.