Preflight requests
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A page signs a customer in by sending JSON to the ShopLite API. The login fails in Chrome, and the server log shows no login at all, only an OPTIONS request. Where did the real request go?
Simple requests and preflighted requests
A simple request is a cross-origin GET, HEAD or POST that sets only safe headers and, if it has a body, a form-like Content-Type. The browser sends it straight away; every other request is preflighted first.
The program below applies the browser rule to six ShopLite calls and prints which ones need a preflight.
Example 1 · Predict the preflight in Java
import java.util.ArrayList;import java.util.List;import java.util.Locale;import java.util.Map;import java.util.Set;import java.util.TreeSet;
public class PreflightDemo {
static final Set<String> SIMPLE_METHODS = Set.of("GET", "HEAD", "POST"); static final Set<String> SAFE_HEADERS = Set.of("accept", "accept-language", "content-language", "content-type"); static final Set<String> SIMPLE_CONTENT_TYPES = Set.of("application/x-www-form-urlencoded", "multipart/form-data", "text/plain");
// A simplified version of the browser's rule (the Fetch standard has a few more details) static String predict(String method, Map<String, String> headers) { TreeSet<String> unsafe = new TreeSet<>(); // sorted, like the browser sends them for (Map.Entry<String, String> h : headers.entrySet()) { String name = h.getKey().toLowerCase(Locale.ROOT); if (!SAFE_HEADERS.contains(name)) { unsafe.add(name); } else if (name.equals("content-type")) { String type = h.getValue().split(";")[0].trim().toLowerCase(Locale.ROOT); if (!SIMPLE_CONTENT_TYPES.contains(type)) { unsafe.add(name); } } } if (SIMPLE_METHODS.contains(method) && unsafe.isEmpty()) { return "simple request, no preflight"; } List<String> lines = new ArrayList<>(); lines.add("PREFLIGHT OPTIONS with Access-Control-Request-Method: " + method); if (!unsafe.isEmpty()) { lines.add(" and Access-Control-Request-Headers: " + String.join(",", unsafe)); } return String.join("\n", lines); }
static void show(String label, String method, Map<String, String> headers) { System.out.println(label); System.out.println(" " + predict(method, headers).replace("\n", "\n ")); }
public static void main(String[] args) { show("1. GET /products", "GET", Map.of()); show("2. GET /me/orders with a token", "GET", Map.of("Authorization", "Bearer eyJ...")); show("3. POST /auth/login with a JSON body", "POST", Map.of("Content-Type", "application/json")); show("4. POST a form (text/plain)", "POST", Map.of("Content-Type", "text/plain;charset=UTF-8")); show("5. DELETE /products/16 with a token", "DELETE", Map.of("Authorization", "Bearer eyJ...")); show("6. PATCH JSON with a token and X-Trace-Id", "PATCH", Map.of("Authorization", "Bearer eyJ...", "Content-Type", "application/json", "X-Trace-Id", "a1")); }}1. GET /products
simple request, no preflight
2. GET /me/orders with a token
PREFLIGHT OPTIONS with Access-Control-Request-Method: GET
and Access-Control-Request-Headers: authorization
3. POST /auth/login with a JSON body
PREFLIGHT OPTIONS with Access-Control-Request-Method: POST
and Access-Control-Request-Headers: content-type
4. POST a form (text/plain)
simple request, no preflight
5. DELETE /products/16 with a token
PREFLIGHT OPTIONS with Access-Control-Request-Method: DELETE
and Access-Control-Request-Headers: authorization
6. PATCH JSON with a token and X-Trace-Id
PREFLIGHT OPTIONS with Access-Control-Request-Method: PATCH
and Access-Control-Request-Headers: authorization,content-type,x-trace-idWhat this code does
- The three sets hold the rule from this section.
Content-Typeis checked by its media type only, sotext/plain;charset=UTF-8(case 4) stays simple whileapplication/json(case 3) does not. - Header names go into a
TreeSetin lower case, so case 6 prints them sorted and comma-separated, exactly as Chrome sent them in the next example.
Why the difference? Forms have always been able to send GET and POST to any site, so servers coped with those long before CORS existed. A DELETE, a JSON body or an Authorization header from a web page was impossible before CORS, and an old server could have trusted that, so the browser asks first. The rule is the common case and leaves out a few rare details of the Fetch standard.
A request is simple only when all of these hold:
- Method is
GET,HEADorPOST. - The page sets only safe request headers:
Accept,Accept-Language,Content-LanguageandContent-Type. Content-Type, if set, istext/plain,application/x-www-form-urlencodedormultipart/form-data(a; charset=...part does not matter).- Break any one of these and the request is preflighted.
Predict the output
Preflight or not?
The page is on http://localhost:3000. Pick what the browser does before the call.
Round 1 of 3
A public search, with no custom headers.
Authorization header or any custom header such as X-Client is preflighted.The OPTIONS preflight request
A preflight is an OPTIONS request the browser sends first, to ask the server whether the real request may follow. It carries the page origin and the wanted method and headers, but no body, no cookies and no token.
The preflight goes to the same URL as the real call. The page below sends five calls to a tiny JDK server that logs every request and sends no CORS headers.
const API = 'http://localhost:9000';const token = 'Bearer eyJhbGciOiJIUzI1NiJ9.demo';async function send(path, options) { try { await fetch(API + path, options); } catch (error) { /* blocked */ }}async function main() { await send('/products', {}); await send('/me/orders', { headers: { Authorization: token } }); await send('/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"email":"asha.rao@example.com"}' }); await send('/feedback', { method: 'POST', headers: { 'Content-Type': 'text/plain' }, body: 'Fast delivery' }); await send('/products/16', { method: 'DELETE', headers: { Authorization: token } });}main();Example 2 · What actually reaches the server
Runs in: a terminal (java RequestLogServer.java), with the page from this section open on http://localhost:3000 in Chrome
import com.sun.net.httpserver.Headers;import com.sun.net.httpserver.HttpServer;import java.net.InetSocketAddress;
// Prints every request the browser sends, and answers 204 with no CORS headers at allpublic class RequestLogServer { public static void main(String[] args) throws Exception { int port = args.length > 0 ? Integer.parseInt(args[0]) : 9000; HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0); server.createContext("/", exchange -> { Headers h = exchange.getRequestHeaders(); System.out.printf("%-7s %-18s ACRM=%-6s ACRH=%-32s Authorization=%s%n", exchange.getRequestMethod(), exchange.getRequestURI(), h.getFirst("Access-Control-Request-Method"), h.getFirst("Access-Control-Request-Headers"), h.getFirst("Authorization") == null ? "no" : "yes"); exchange.sendResponseHeaders(204, -1); exchange.close(); }); server.start(); System.out.println("Listening on http://localhost:" + port); }}Listening on http://localhost:9000 GET /products ACRM=null ACRH=null Authorization=no OPTIONS /me/orders ACRM=GET ACRH=authorization Authorization=no OPTIONS /auth/login ACRM=POST ACRH=content-type Authorization=no POST /feedback ACRM=null ACRH=null Authorization=no OPTIONS /products/16 ACRM=DELETE ACRH=authorization Authorization=no
What this code does
- Only the simple calls (
GET /productsand thetext/plainPOST /feedback) arrived as themselves. The other three arrived asOPTIONSwith the method and header names, and never with the token (Authorization=no). - This server sends no CORS headers, so every preflight failed and the browser never sent the real
GET /me/orders,POST /auth/loginorDELETE. The simplePOST /feedbackdid run on the server, even though the page could not read the answer.
A preflight has three headers:
Origin: the page's origin.Access-Control-Request-Method: the method the page wants to use.Access-Control-Request-Headers: the non-safe header names it wants to send, in lower case, sorted and separated by commas.
OPTIONS, every preflight fails with 401 before CORS can answer. The Configuring CORS lesson fixes exactly this.The answer: Allow-Methods, Allow-Headers and Max-Age
Access-Control-Allow-Methods and Access-Control-Allow-Headers are the preflight answer headers that list the methods and request headers the page may use. The browser sends the real request only if both lists cover what it asked for.
The next curl call sends the login preflight to the ShopLite API, which already has CORS set up for the page on port 3000.
Example 3 · The ShopLite API answers the login preflight
Runs in: a terminal, with the ShopLite API (dev profile, CORS configured) running on port 8080
curl -i -X OPTIONS http://localhost:8080/api/v1/auth/login \ -H "Origin: http://localhost:3000" \ -H "Access-Control-Request-Method: POST" \ -H "Access-Control-Request-Headers: content-type"HTTP/1.1 200 Vary: Origin Vary: Access-Control-Request-Method Vary: Access-Control-Request-Headers Access-Control-Allow-Origin: http://localhost:3000 Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE Access-Control-Allow-Headers: content-type Access-Control-Expose-Headers: Location Access-Control-Max-Age: 3600 Content-Length: 0 Date: Fri, 16 Oct 2026 08:05:13 GMT
What this code does
200with an empty body: the preflight is a question, so there is nothing to return.Access-Control-Allow-Methodslists every method ShopLite allows, andAccess-Control-Allow-Headersechoes the requested header because it is on the allow-list.Access-Control-Max-Age: 3600lets the browser skip this question for an hour. The login controller never ran: Spring's CORS processing answered the preflight on its own.
Example 4 · The preflight cache in the Network tab
Runs in: Chrome developer tools, Network tab, with the ShopLite browser client on http://localhost:3000
First sign-in after opening the page OPTIONS /api/v1/auth/login 200 preflight POST /api/v1/auth/login 200 OPTIONS /api/v1/me/orders?size=10 200 preflight GET /api/v1/me/orders?size=10 200Page reloaded, signed in again a few minutes later POST /api/v1/auth/login 200 GET /api/v1/me/orders?size=10 200Requests: 4 on the first visit, 2 on the second. The preflight answers had Access-Control-Max-Age: 3600, so for one hour Chrome reuses them for the same origin, URL, method and headers, even after a page reload.
What this code does
- The first visit pays one extra round trip per URL. The second sign-in happened after a page reload a few minutes later and went straight to
POSTandGET: the cached preflight answers were still valid. - The cache is keyed by URL too, so
/api/v1/me/orders?size=10and/api/v1/me/orders?size=20each get their own preflight.
A successful preflight answer is usually 200 with no body. Access-Control-Allow-Origin names the page's origin, and the browser checks that the method and every requested header are in the two lists. If one is missing, the browser never sends the real request: the server log shows only the OPTIONS call, and the console shows Response to preflight request doesn't pass access control check.
Access-Control-Max-Age says how many seconds the browser may reuse the answer for the same origin, URL, method and headers. Without it, Chrome keeps the answer for only 5 seconds, so a page that polls an API would double its requests. Browsers also cap it: Chrome at 7,200 seconds (2 hours) and Firefox at 86,400 (24 hours), so a bigger value changes nothing.
Fix the error
Fix the preflight answer
Chrome blocks the call after the preflight. Pick the replacement for the highlighted line.
Round 1 of 2
The page adds an X-Trace-Id header to its calls.
Error
Request header field x-trace-id is not allowed by Access-Control-Allow-Headers in preflight response.
Why a JSON body or an Authorization header always triggers one
Two things ShopLite's frontend does on almost every call break the simple-request rule, as these three calls show.
fetch(API + '/auth/login', { // preflight: JSON body method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password })});fetch(API + '/me/orders', { // preflight: Authorization header headers: { Authorization: 'Bearer ' + accessToken }});fetch(API + '/products?q=redmi'); // simple: no preflightA JSON body needs Content-Type: application/json, which is not one of the three form types. A signed-in call needs Authorization: Bearer ..., which is not a safe header. So POST /api/v1/auth/login and every /api/v1/me/... call are preflighted, always. Only public reads with no custom headers stay simple.
Do not add headers "just in case": a Content-Type: application/json on a GET (which has no body) or an X-Client header turns every search into two requests. A token-based API is also easier to protect, because the browser asks before sending any token-carrying request, and the server's CORS settings decide which origins get a "yes".
Simulating a preflight with curl
curl -X OPTIONS with an Origin header and the two Access-Control-Request-* headers sends exactly what the browser would send.
Example 5 · Preflight for a signed-in call
Runs in: a terminal, with the ShopLite API (dev profile, CORS configured) running on port 8080
curl -i -X OPTIONS http://localhost:8080/api/v1/me/orders \ -H "Origin: http://localhost:3000" \ -H "Access-Control-Request-Method: GET" \ -H "Access-Control-Request-Headers: authorization"HTTP/1.1 200 Vary: Origin Vary: Access-Control-Request-Method Vary: Access-Control-Request-Headers Access-Control-Allow-Origin: http://localhost:3000 Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE Access-Control-Allow-Headers: authorization Access-Control-Expose-Headers: Location Access-Control-Max-Age: 3600 Content-Length: 0 Date: Fri, 16 Oct 2026 08:05:13 GMT
What this code does
/api/v1/me/ordersneeds a signed-in customer, yet the preflight got200without any token. That is required: the browser will not send the token until this answer says yes.Access-Control-Allow-Headers: authorizationis the line that matters for this call. Without it, Chrome would refuse to send theAuthorizationheader and the realGETwould never happen.
Example 6 · Preflights the server refuses
Runs in: a terminal, with the ShopLite API (dev profile, CORS configured) running on port 8080
# 1. an origin that is not on the listcurl -i -X OPTIONS http://localhost:8080/api/v1/me/orders \ -H "Origin: https://evil.example" \ -H "Access-Control-Request-Method: GET" \ -H "Access-Control-Request-Headers: authorization"# 2. the right origin, plus a header the API does not allowcurl -i -X OPTIONS http://localhost:8080/api/v1/me/orders \ -H "Origin: http://localhost:3000" \ -H "Access-Control-Request-Method: GET" \ -H "Access-Control-Request-Headers: authorization,x-trace-id"HTTP/1.1 403 Vary: Origin Vary: Access-Control-Request-Method Vary: Access-Control-Request-Headers Transfer-Encoding: chunked Date: Fri, 16 Oct 2026 08:05:13 GMT Invalid CORS request HTTP/1.1 200 Vary: Origin Vary: Access-Control-Request-Method Vary: Access-Control-Request-Headers Access-Control-Allow-Origin: http://localhost:3000 Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE Access-Control-Allow-Headers: authorization Access-Control-Expose-Headers: Location Access-Control-Max-Age: 3600 Content-Length: 0 Date: Fri, 16 Oct 2026 08:05:14 GMT
What this code does
- An unknown origin gets
403and the plain textInvalid CORS request, with noAccess-Control-Allow-Origin. The browser reports it as a failed preflight. - For the extra header, Spring 7 answers
200but lists onlyauthorization. The browser compares the list with what it asked for and blocks the call:Request header field x-trace-id is not allowed by Access-Control-Allow-Headers in preflight response.
Curl shows the raw answer, not just the browser's verdict, so it is the fastest way to test a server's CORS settings. Check three cases:
- The real frontend origin: expect
200and theAccess-Control-Allow-*headers. - An unknown origin: Spring answers
403with the textInvalid CORS request. - A header your frontend does not send: it must not appear in
Access-Control-Allow-Headers.
Access-Control-Request-Method header, curl's OPTIONS is not a preflight at all, just an ordinary OPTIONS request, and you test the wrong thing.Next step
Check your understanding
11 quick questions