QA Interview Hub · Knowledge base · Quizzes · Українська

API › Headers, caching and CORS

CORS and preflight

CORS is a browser mechanism by which a server lets JavaScript from another origin read its responses; Postman and curl do not apply it. For a JSON body, an Authorization header or the PUT, PATCH and DELETE methods the browser first sends a preflight OPTIONS. The Origin is compared with an allowlist rather than reflected together with Allow-Credentials, and CORS does not replace server-side authorization.

API · CORS

The request passes in Postman, but the browser shows a red CORS error. Whose problem is it?

A front end on https://app.bank.test calls an API on https://api.bank.test. Everything works in Postman, in the browser the request never arrives, and the console says access was blocked by CORS policy. Developers argue about who is to blame. To test it rather than argue, you need to know what CORS does and what it does not.

This lesson explains why CORS exists, how a preflight works, which headers the server must return and how to check them without a browser.

How it is built

By default a browser follows the same-origin policy: a page from one origin (scheme, domain and port) cannot read responses from another. Without it, any site could read a user's accounts on behalf of a bank the user is signed in to in a neighbouring tab. CORS (cross-origin resource sharing) is how a server allows the browser to make an exception: in its response it names the origin that may read.

It matters what CORS does not do. It is a browser restriction, and only that. Postman, curl and server-side clients do not apply it, so "works in Postman" proves nothing. CORS also does not protect the server from a request: it protects the user from another site reading the response. The request from a foreign origin may still reach the server and be executed.

Preflight. "Simple" requests (GET, HEAD, POST with headers from the safe list and Content-Type only application/x-www-form-urlencoded, multipart/form-data or text/plain) the browser sends at once. Everything else, including a JSON body, an Authorization header or the methods PUT, PATCH and DELETE, the browser first "asks about" with an OPTIONS request, to see whether the server allows it. Only after a positive answer does the real request go.

Preflight before the main request

BrowserServerOPTIONS + Origin (preflight)204 + Access-Control-Allow-*POST /api/transfers201 + Allow-Origin
Figure 1. The first exchange is the check, the second is the real request. If the server did not allow it in the first, the browser never sends the second.

A preflight looks like this:

curl -i -X OPTIONS "$BASE/api/transfers" \
  -H "Origin: https://app.bank.test" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: authorization, content-type"

A correct response:

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.bank.test
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: authorization, content-type
Access-Control-Max-Age: 600
Vary: Origin

Access-Control-Allow-Origin names the allowed origin, Allow-Methods and Allow-Headers list what may be sent, Max-Age says for how many seconds the browser remembers this answer (so it does not ask every time). Vary: Origin is needed when the value of Allow-Origin depends on who asks, otherwise a cache serves one origin's answer to another. The Access-Control-Allow-Credentials: true flag allows requests with cookies. On the client side that needs credentials: 'include', and the server then cannot answer Allow-Origin: *.

Example: a CORS defect only a test can see

Before. A developer "fixed" a CORS error like this: the server reflects any Origin into Allow-Origin and adds Allow-Credentials: true. Everything works in the browser, and nobody notices the defect. A request from a foreign origin shows it:

# request had  Origin: https://evil.test
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://evil.test
Access-Control-Allow-Credentials: true

Now any site opened in a tab of a signed-in user can read that user's data: the browser sends the cookie and hands the response to a foreign script. This is a serious vulnerability, and it passes every functional test because our own front end works.

After. A test pair: the allowed origin gets its header, a foreign one gets nothing.

const APP = 'https://app.bank.test';

async function preflight(request: APIRequestContext, origin: string) {
  return request.fetch('/api/transfers', {
    method: 'OPTIONS',
    headers: {
      Origin: origin,
      'Access-Control-Request-Method': 'POST',
      'Access-Control-Request-Headers': 'authorization, content-type',
    },
  });
}

test('the app origin is allowed', async ({ request }) => {
  const res = await preflight(request, APP);
  expect(res.status()).toBeLessThan(300);
  const h = res.headers();
  expect(h['access-control-allow-origin']).toBe(APP);
  expect(h['access-control-allow-headers']).toContain('authorization');
});

test('a foreign origin is not allowed', async ({ request }) => {
  const res = await preflight(request, 'https://evil.test');
  const h = res.headers();
  expect(h['access-control-allow-origin']).not.toBe('https://evil.test');
  expect(h['access-control-allow-origin']).not.toBe('*');
});

Playwright request does not apply CORS, so it sends OPTIONS with any Origin and lets you read the response headers. That is exactly the needed check: we test what the server says, not how a browser interprets it. For a final check in a real browser, open page.goto(APP) and run fetch to the API inside page.evaluate: if CORS is broken the request fails with a TypeError, and the message is visible through page.on('console').

Limits and alternatives

  • The Authorization header is not covered by * in Access-Control-Allow-Headers: it must be listed explicitly. A common configuration mistake: * is set, yet a request with a token fails on the preflight.
  • The preflight response must be successful (2xx) and must not require authorisation: the browser adds neither a token nor a cookie to it. If a gateway returns 401 or 404 for OPTIONS, nothing will work.
  • For JavaScript to read response headers outside the safelist (X-Request-Id, Location, ETag), the server must list them in Access-Control-Expose-Headers. Without it a script sees only a small set of safe headers.
  • Browsers cap Access-Control-Max-Age with their own ceiling (2 hours in Chromium, 24 hours in Firefox), so a larger value has no effect.
  • An alternative to CORS: serve the front end and the API from one origin or through a shared reverse proxy. Then there are no cross-origin requests and the preflight disappears.
  • The Origin header can be forged outside a browser. CORS does not replace server-side authorisation.

Common mistakes

  • Checking CORS in Postman. It does not apply it, so "all fine" proves nothing.
  • Reflecting an arbitrary Origin together with credentials. This opens the user's data to any site. The origin is compared with a list of allowed ones.
  • Setting Allow-Origin: * for an API with cookies. The browser rejects such a credentialed request anyway, but for an open public API without cookies * is perfectly fine. The rule depends on whether cookies are involved.
  • Forgetting Vary: Origin. A cache stores the response for one origin and serves it to another.
  • Allowing the wrong methods and headers. The front end suddenly gets a feature with PATCH or X-Custom, and the preflight knows nothing about them.

Check yourself

A request returns 200 in Postman, but the browser blocks it from the front end. What do you check first?

Answer

The response to the preflight OPTIONS with the front end's Origin: is there an Access-Control-Allow-Origin with that origin, are the needed methods and headers listed (authorization in particular), and does the preflight return 2xx without requiring authorisation. Postman does not apply CORS, so 200 there says nothing.

For a request with Origin: https://evil.test the server returns Allow-Origin: https://evil.test and Allow-Credentials: true. Is it a defect?

Answer

Yes, a serious one: any site will be able to read the data of a signed-in user. The origin must be compared with a list of allowed ones, not reflected. For a foreign origin the server should not return Allow-Origin at all.

In an interview. Junior: CORS is a browser mechanism: it lets JavaScript from one origin read responses from another if the server allowed it. That is why Postman does not show it. For JSON requests the browser first sends a preflight OPTIONS. Middle/Senior: I check that an allowed origin gets exact Allow-Origin, Allow-Methods and Allow-Headers (with authorization listed explicitly), and a foreign one gets nothing. I also check that the server does not reflect an arbitrary Origin together with Allow-Credentials: true, that the preflight without authorisation returns 2xx and that Vary: Origin is present. CORS does not protect the server, so it complements authorisation and does not replace it.

More articles in this chapter