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

API

Headers, caching and CORS

Key headers

Headers are message metadata that clients, proxies, gateways and caches act on, including Content-Type, Accept, Location, Cache-Control and Set-Cookie. A correct body with the right status does not prove the response is right: a wrong Content-Type, a missing Location or a cookie without Secure, HttpOnly and SameSite goes unnoticed. They are checked on both successful and error responses.

API · Headers

The body is right, the status is 201, yet the client cannot open the resource. What is in the headers?

After a transfer is created the API returns 201 and correct JSON, yet the mobile client opens nothing. The response has no Location, Content-Type says text/html, the X-Powered-By header shows the framework version, and the session cookie arrived without a single security attribute. None of these defects is visible in the body.

Headers are the metadata of a message. This lesson covers how they are built, which of them to check in every response, and how to catch a defect that the body hides.

How it is built

A header is a "name: value" pair placed before the message body (RFC 9110). They exist because proxies, gateways and caches sit between the client and the server, and they do not parse bodies, they act on metadata only. Headers answer four questions: what is in the body (Content-Type), what the client wants (Accept), who you are (Authorization, Cookie) and what to do next (Location, Cache-Control, Retry-After).

HeaderWhereWhat for
Content-TypeRequest and responseBody format, for example application/json
AcceptRequestWhich format the client wants back
AuthorizationRequestA token or credentials
LocationResponseURL of the created resource or of a redirect
Cache-ControlResponseCaching rules
ETagResponseResource version for caching and concurrent updates
Retry-AfterResponseWhen to retry after 429 or 503
Set-CookieResponseA cookie with security attributes

Format negotiation. The client says in Accept what it can read, the server says in Content-Type what it sent. If the requested format does not exist, RFC 9110 allows 406 Not Acceptable but does not require it: the server may also ignore Accept and return a default format. What a particular API does is set by its contract, so the test is written against the documentation, not against "correct" textbook behaviour.

Format negotiation

ClientServerAccept: application/json200, Content-Type: application/jsonAccept: application/xml406 or JSON by default
Figure 1. The client asks for a format, the server names the one it sent. The answer to an unsupported format is set by the contract: 406 or silent JSON, but never an HTML error page.

Example: a response whose body is right and headers are not

Before. The test checks status === 201 and body.id, and it is green on this response:

HTTP/1.1 201 Created
Content-Type: text/html; charset=utf-8
X-Powered-By: Express/4.17.1
Set-Cookie: sid=9f2c1e; Path=/

{ "id": "tr_91", "status": "pending" }

Read it by its headers. Content-Type: text/html for JSON: clients and proxies that trust the type will not parse the body, and a browser with nosniff refuses to treat it as a script. There is no Location, so the client does not know where to find the created resource. X-Powered-By: Express/4.17.1 tells an attacker which known vulnerabilities to look for. A cookie without Secure, HttpOnly and SameSite can be stolen by a script or intercepted over HTTP.

After. The correct response:

HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Location: /v1/transfers/tr_91
Set-Cookie: sid=9f2c1e; Path=/; Secure; HttpOnly; SameSite=Lax

{ "id": "tr_91", "status": "pending" }

And a test that catches it instead of guessing:

import { test, expect } from '@playwright/test';

test('create transfer: response headers', async ({ request }) => {
  const res = await request.post('/v1/transfers', {
    data: { toAccount: 'UA21...', amount: 150, currency: 'UAH' },
  });
  expect(res.status()).toBe(201);

  const h = res.headers(); // names are lower case
  expect(h['content-type']).toMatch(/^application\/json/);
  expect(h['location']).toMatch(/^\/v1\/transfers\/tr_\w+$/);
  expect(h['x-powered-by']).toBeUndefined();

  const cookies = res.headersArray().filter((x) => x.name.toLowerCase() === 'set-cookie');
  for (const c of cookies) {
    expect(c.value).toContain('HttpOnly');
    expect(c.value).toContain('Secure');
    expect(c.value).toMatch(/SameSite=(Lax|Strict)/i);
  }
});

Reading headers by lower-case name is convenient here: Playwright returns headers() in lower case. Headers that repeat (Set-Cookie) need headersArray(), because the headers() object joins values into one string.

A negative case for format negotiation takes one request:

# the client asks for a format the API does not offer
curl -i "$BASE/v1/transfers/tr_91" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Accept: application/xml"

# expected by the contract: 406 Not Acceptable, or JSON if the
# contract says "Accept is ignored". Not an HTML error page.

Limits and alternatives

  • Header names are case-insensitive, while values depend on the header: media type and subtype are case-insensitive too under RFC 9110, but some clients compare application/json and Application/JSON as plain strings. Only the name is compared without case, and the type in the value is checked with a regular expression that tolerates a trailing charset.
  • Some headers are added not by the API but by a proxy, gateway or CDN (Via, X-Request-Id, Server). A defect there may be a gateway setting rather than service code, so test the same path users take.
  • In Postman the client itself adds some headers (User-Agent, Postman-Token, Accept-Encoding). They are hidden on the Headers tab (the hidden toggle) and visible in the Postman console, so "works in Postman" does not mean it works without them.
  • A browser front end does not see all response headers: cross-origin requests need Access-Control-Expose-Headers (see the CORS lesson). An API-level test will not show that.

Common mistakes

  • Checking only the body and the status. A wrong Content-Type, a missing Location and cookies without flags go unnoticed and break the client or security later.
  • Expecting 406 by default. Not every API returns it, and a test written "by the textbook" reports a false defect. Contract first, case second.
  • Comparing content-type for exact equality. application/json; charset=utf-8 is not equal to application/json, and the test fails without a defect. Check the start of the string.
  • Not checking headers on errors. 404 and 500 also need the right Content-Type, and that is sometimes where X-Powered-By leaks.

Check yourself

The API ignores Accept: application/xml and returns JSON with status 200. Is it a bug?

Answer

Not necessarily. RFC 9110 allows both 406 and returning a default format. It is a bug if the contract promises 406, or if Content-Type says application/xml while the body is JSON. Check the documentation first.

The response has Set-Cookie: sid=abc; Path=/. What is wrong and why is it dangerous?

Answer

There is no HttpOnly (a page script, including one injected through XSS, can read the session), no Secure (the cookie also travels over plain HTTP) and no SameSite (a browser that does not default to Lax sends it from other sites too, which opens the way to CSRF).

In an interview. Junior: Headers are the metadata of a request and a response. I look at Content-Type, Location after creation, Authorization in the request and the cookie attributes. Middle/Senior: A body with the right status does not prove the response is right: the client, proxies and the browser act on headers. I check the content type with charset in mind, Location, the cookie flags and the absence of X-Powered-By, on both successful and error responses. I match the reaction to an unsupported Accept against the contract, because the RFC allows both 406 and a default format.

ETag, 304 and Cache-Control

An ETag is a version of a resource: the client sends it in If-None-Match, and if nothing changed the server answers 304 Not Modified without a body. Cache-Control manages caching: max-age sets freshness, no-cache allows storing but requires revalidation, no-store forbids storing, and private excludes shared caches. A cache is tested with a sequence of requests, and personal data gets no-store or private.

API · Cache

One user's balance suddenly shows up for another. Which header allowed it?

A user opens "My accounts" and sees someone else's balance. The database and the authorisation code are fine: the response with personal data had Cache-Control: public, max-age=300, and a CDN served it to the next requester. A single-request test does not show this, because the defect appears only when a cache sits between the client and the server.

This lesson covers how conditional requests with ETag work, what the Cache-Control directives mean, and what to check so you miss neither an unwanted cache nor broken validation.

How it is built

Caching (RFC 9111) solves two problems: not downloading the same thing again, and not serving stale data. There are two mechanisms. Freshness: Cache-Control: max-age=60 says a cache may serve the response for 60 seconds without asking the server. Validation: when freshness runs out, the client asks the server "is my version still current?". The version is marked by the ETag validator, and the question is the If-None-Match header. If nothing changed, the server answers 304 Not Modified with no body, and the client uses what it stored. If it changed, it is an ordinary 200 with a new body and a new ETag.

A conditional request with ETag

ClientServerGET /accounts/42200 + ETag: "v7" + bodyGET + If-None-Match: "v7"304 with no body
Figure 1. The second exchange is shorter: no body is sent, the client takes it from its own cache. Traffic is saved, but the request to the server still happens.

The same ETag works the other way, as protection against lost updates. The client reads a resource together with ETag: "v7", edits it and sends PUT with If-Match: "v7". If someone changed the resource meanwhile, the version is different now, and the server answers 412 Precondition Failed instead of silently overwriting someone else's edit. Some APIs require If-Match and answer 428 Precondition Required when it is missing.

Cache-Control: what each directive means

  • max-age=60: the response is fresh for 60 seconds, during which a cache does not ask the server.
  • no-cache: it may be stored, but must be validated before every use (via ETag or a date). The name is misleading: there is plenty of cache here.
  • no-store: do not store the response anywhere, neither in the browser nor in intermediate caches.
  • private: may be stored only in a single user's cache (the browser), not in shared ones (CDN, proxy). public: shared caches may store it too.
  • must-revalidate: a stale response must not be served without validation, even if the server is unreachable.

no-cache and no-store

no-cache

The response is stored, but a cache asks the server before every use. Fits data that changes but is not secret.

no-store

Nothing is stored. Fits balances, tokens and personal data, where a copy on disk is already a problem.

Figure 2. Both directives are right, but for different data. The mistake is treating them as synonyms.

Example: from "it works" to checking caching and versions

Before: the test makes one GET /accounts/42 and looks at the body. Below is a manual validation check with curl (lines starting with # are the expected result, not output):

curl -i "$BASE/v1/accounts/42" -H "Authorization: Bearer $TOKEN"
# HTTP/1.1 200 OK
# ETag: "v7"
# Cache-Control: private, no-cache

curl -i "$BASE/v1/accounts/42" -H "Authorization: Bearer $TOKEN" \
  -H 'If-None-Match: "v7"'
# HTTP/1.1 304 Not Modified   (no body, ETag: "v7" again)

A second request with no body and status 304 means validation works. Next we move this into an automated test that also checks the other side: an old ETag after a change does not give 304, and a stale If-Match gives 412.

test('ETag changes after an update, a stale If-Match gives 412', async ({ request }) => {
  const first = await request.get('/v1/accounts/42');
  const etag = first.headers()['etag'];
  expect(etag).toBeTruthy();

  const same = await request.get('/v1/accounts/42', {
    headers: { 'If-None-Match': etag },
  });
  expect(same.status()).toBe(304);
  expect(await same.text()).toBe('');

  const upd = await request.patch('/v1/accounts/42', {
    data: { nickname: 'main' },
    headers: { 'If-Match': etag },
  });
  expect(upd.ok()).toBeTruthy();
  expect((await request.get('/v1/accounts/42')).headers()['etag']).not.toBe(etag);

  const stale = await request.patch('/v1/accounts/42', {
    data: { nickname: 'other' },
    headers: { 'If-Match': etag }, // the old version
  });
  expect(stale.status()).toBe(412);
});

Four different defects are covered by one scenario: the server does not return ETag, returns 304 with a body, does not change ETag after an update, or lets someone else's edit be overwritten. The first request stores the version, the second proves that 304 is empty, the third and fourth look at behaviour after the change.

Responses with personal data are checked separately:

test('private data is not stored by shared caches', async ({ request }) => {
  const res = await request.get('/v1/accounts/42/balance');
  const cc = res.headers()['cache-control'] ?? '';
  expect(cc).toMatch(/no-store|private/);
  expect(cc).not.toMatch(/public/);
});

This is a cheap test for a catastrophic defect: a balance or profile response in a shared cache. If there are no directives at all, a cache may apply a heuristic based on Last-Modified and store the response on its own, so a missing Cache-Control on a personal response is also worth a remark. A shared cache will not store a response to a request with Authorization without public, s-maxage or must-revalidate, but it will store one authenticated by a cookie.

One more request pair is useful for a manual check: 412 shows that resource versioning is actually enforced.

PUT /v1/accounts/42 HTTP/1.1
If-Match: "v7"
Content-Type: application/json

{ "nickname": "main" }

HTTP/1.1 412 Precondition Failed

Limits and alternatives

  • A weak validator W/"v7" means "semantically the same", not byte for byte. That is enough for If-None-Match, while If-Match (a write) needs a strong one.
  • Instead of ETag there is the Last-Modified / If-Modified-Since pair: second precision, so it may miss quick changes. ETag is more reliable.
  • Playwright request caches nothing itself, so this test cannot verify the browser cache or the CDN cache. It checks only the headers the server returned. Cache behaviour is observed in the browser Network tab (the Size column shows "disk cache", the Status column shows 304) and on the cache that sits in front of the test environment.
  • Static files with a hash in the name (app.3f9a.js) get max-age of a year and immutable. A JSON API must not do this.
  • ETag with If-Match is not the only way to version: some APIs put the version in the body ("version": 7) and compare it themselves. Then 409 is returned instead of 412, which also has to be matched against the contract.

Common mistakes

  • Confusing no-cache and no-store. A developer puts no-cache on a balance and thinks there is no caching. A copy is stored, and on a shared cache that is a leak.
  • Testing the cache with one request. The defect shows only in a sequence: the first request, a repeat with a validator, a request after a change.
  • Expecting 304 with a body. A 304 response has no body. A body in it means a defect, or a proxy that "added" something.
  • Not changing the ETag after an update. The client then sees 304 forever and never gets new data. It is a silent bug visible only on a repeat request.
  • Putting public on authorised responses. A shared cache does not know the response depends on the token and serves it to everyone.

Check yourself

The client sends If-None-Match: "v7" and the server answers 200 with the same ETag: "v7" and a full body. What does it mean?

Answer

The server does not support conditional requests: it should answer 304 with no body because the version did not change. The data is functionally right, but there is extra traffic. It is a remark about performance, not correctness.

The response to GET /accounts/42/balance has Cache-Control: no-cache. Is that enough?

Answer

No, if the balance must not be stored. no-cache allows a copy to be stored and only requires validation before use. For personal data expect no-store or at least private, so a shared cache does not hold someone else's data.

In an interview. Junior: ETag is a resource version. The client sends it in If-None-Match, and if nothing changed the server answers 304 with no body. no-cache means "validate before use", no-store means "do not store". Middle/Senior: I test caching with a sequence of requests: the first, a repeat with a validator (I expect an empty 304), a request after a change (a new ETag, and the old one gets 200). I check a stale version in If-Match for 412, which protects against lost updates. For personal and financial data I expect no-store or private, because public lets a shared cache store a response even to a request with Authorization, which ends in someone else's balance leaking.

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.

Reading a CORS error in the browser console

Access to fetch at 'https://api.bank.test/api/transfers'
1from origin 'https://app.bank.test' has been blocked by CORS policy:
2Response to preflight request doesn't pass access control check:
3No 'Access-Control-Allow-Origin' header is present on the requested resource.
4TypeError: Failed to fetch
  1. Who asks: the origin of the page. This is the one the server must allow.
  2. Where it failed: on the preflight (OPTIONS). The browser never even sent the main request.
  3. Why: the preflight response has no Access-Control-Allow-Origin.
  4. What the code sees: only a generic fetch failure, with no status and no body.

What to do

Send the same OPTIONS with curl, with the Origin and Access-Control-Request-* headers, and read the response headers. Postman will not show this error, because only the browser applies CORS.

Figure 2. A typical CORS message in the Chrome console (shortened): it shows what exactly the server did not allow.

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.

Service headers: Retry-After, rate limits, Vary and security

Service headers carry no business data but steer the behaviour of the client, cache and browser. Retry-After in 429 and 503 responses says when to retry, Vary lists the request headers the response depends on, and HSTS, nosniff and stripped versions in Server protect the response. The X-RateLimit-* names are not a standard and come from the documentation. Security headers are checked on errors too and through the gateway.

API · Service headers

A client gets 429 and immediately retries in a loop. What is missing from the response?

An API under load returns 429 with no hint of when to retry. The client does not know how long to wait and knocks every second, making the overload worse. Elsewhere a CDN serves the Ukrainian version of a banner to English-speaking users because the response has no Vary. The bodies look right in both cases: the defect sits in service headers.

This lesson is about headers that report the state of the service, steer the cache between different clients and protect the response: what they mean, why they are easy to miss and how to check them.

How it is built

Service headers carry no business data, but they decide how the client, the browser and the cache treat the response. By purpose they fall into four groups.

Limits and retry. A 429 Too Many Requests or 503 Service Unavailable response should include Retry-After: the RFCs allow it but do not require it, so the contract sets the expectation. Per RFC 9110 it is either a number of seconds (Retry-After: 30) or an HTTP date (Retry-After: Wed, 11 Nov 2026 12:00:00 GMT). Many APIs also add informational limit headers: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset or RateLimit-* from the IETF draft. There is no single final standard for their names and format, so a test follows the documentation of the specific API, not a "general" template.

The limit counter

request 1 → 200, Remaining: 2request 2 → 200, Remaining: 1request 3 → 200, Remaining: 0request 4 → 429, Retry-After: 30
Figure 1. The counter in the responses should decrease, and 429 should appear exactly after zero. After Retry-After seconds the limit should recover.

Cache between clients: Vary. The Vary header lists the request headers the response depends on: Vary: Accept-Language, Vary: Accept-Encoding, Vary: Origin. A shared cache (CDN, proxy) uses them as part of the key. Without Vary it stores the answer to the first request and serves it to everyone, whoever asks. The defect shows up only when a cache really sits between the client and the server, so a direct test does not see it.

Compression and downloads. The client sends Accept-Encoding: gzip, br, the server answers Content-Encoding: gzip and Vary: Accept-Encoding. For files, Content-Disposition: attachment; filename="report.pdf" asks the browser to save the file rather than display it, while Content-Length and Content-Type describe the content.

Response security.

  • Strict-Transport-Security (HSTS): from now on the browser visits the domain over HTTPS only;
  • X-Content-Type-Options: nosniff: the browser does not guess the content type and trusts Content-Type;
  • Content-Security-Policy (for HTML responses): restricts sources of scripts and resources;
  • Cache-Control: no-store for responses with personal data;
  • no X-Powered-By and no versions in Server: they hint at which vulnerabilities to look for.

Example: a limit that "exists" but does not work

Before. The rate-limit test only checks that 429 arrives after many requests. It is green even if Retry-After is missing or contains garbage. After: the test reads Retry-After, waits that long and proves the limit recovered.

test('429 carries Retry-After and the limit recovers', async ({ request }) => {
  let res = await request.get('/v1/search?q=a');
  for (let i = 0; i < 200 && res.status() !== 429; i++) {
    res = await request.get('/v1/search?q=a');
  }
  expect(res.status()).toBe(429);

  const wait = Number(res.headers()['retry-after']); // seconds form
  expect(Number.isInteger(wait)).toBe(true);
  expect(wait).toBeGreaterThan(0);

  await new Promise((r) => setTimeout(r, wait * 1000 + 200));
  expect((await request.get('/v1/search?q=a')).status()).toBe(200);
});

There are three checks in one scenario: 429 really arrives, Retry-After exists and has a sensible format, and after the wait the service answers 200 again. If the limit window in the test environment is long, shorten it through environment configuration instead of waiting for minutes. If the documentation allows the date form, the test parses that too.

Vary checked by hand:

curl -si "$BASE/v1/banners" -H "Accept-Language: uk" \
  | grep -i -E "^(content-language|cache-control|vary)"
# content-language: uk
# cache-control: public, max-age=300
# (no Vary line: the CDN will serve "uk" to everyone)

Here the response depends on the language, carries a 5-minute public cache, and has no Vary: the CDN will serve "uk" to everyone. The right header would be Vary: Accept-Language. The same check is needed for compression:

curl -si "$BASE/v1/transfers?limit=100" -H "Accept-Encoding: gzip" \
  -H "Authorization: Bearer $TOKEN" -o /dev/null -D - | grep -i -E "encoding|vary"
# content-encoding: gzip
# vary: Accept-Encoding

Security headers are checked on a successful response and on an error, because gateways often add them only on the "happy" path:

test('security and service headers', async ({ request }) => {
  for (const path of ['/v1/health', '/v1/accounts/999999']) { // 200 and 404
    const h = (await request.get(path)).headers();
    expect(h['strict-transport-security']).toContain('max-age=');
    expect(h['x-content-type-options']).toBe('nosniff');
    expect(h['x-powered-by']).toBeUndefined();
    expect(h['server'] ?? '').not.toMatch(/\d/); // no version numbers
  }
});

Limits and alternatives

  • Security headers are mostly set not by service code but by a gateway or reverse proxy. A service-level test that bypasses the gateway will not see them, so check the same URL users use.
  • Retry-After can be checked only when the limit really triggers. On a shared test environment an aggressive request loop disturbs colleagues, so do it with a dedicated key or user.
  • The RateLimit draft changed between versions, so the value format may differ between services. Go by the documentation, not by memory.
  • Content-Security-Policy and HSTS concern browsers. For a pure JSON API CSP makes little sense, while nosniff and HSTS stay useful.
  • Without Accept-Encoding in the request RFC 9110 treats any content coding as acceptable, so a compressed answer is not a violation, though a client that cannot decompress will not read it. A server may also skip compressing a small body, which is normal: the threshold is a configuration setting.

Common mistakes

  • Checking only status 429. Without Retry-After the client retries in a loop and worsens the overload, and the test does not notice.
  • Treating X-RateLimit-* as a standard. Names differ between APIs, so the expected names come from the documentation.
  • Skipping Vary because "everything works". The defect appears only with a cache between client and server, and a direct test does not show it.
  • Checking security headers on 200 only. On 404 and 500 they are often missing, and that is exactly where versions leak.
  • Leaving Server: nginx/1.18.0. A specific version helps pick a known vulnerability.

Check yourself

An API returns 429 without Retry-After. Why is it a defect if the status is right?

Answer

The client does not know how long to wait and retries at once or by its own heuristic, which increases the load. A proper 429 says when to retry. Without it rate limiting works as blocking, not as a managed delay.

An endpoint returns the user's language by Accept-Language, has Cache-Control: public, max-age=300 and no Vary. What goes wrong and how do you reproduce it?

Answer

A shared cache stores the answer to the first request (say, Ukrainian) and serves it to everyone who asks in the next 5 minutes. It can be reproduced only with a cache between client and server: send requests with different Accept-Language through a CDN or proxy and compare the responses. The fix is to add Vary: Accept-Language.

In an interview. Junior: A 429 and a 503 should include Retry-After, and Vary tells a cache which request headers the response depends on. For security I check HSTS, nosniff and the absence of versions in Server and X-Powered-By. Middle/Senior: For a limit I run a full scenario: the counter decreases, 429 arrives after zero with Retry-After, and after the wait the limit recovers. I take the X-RateLimit-* names from the documentation because there is no standard. A missing Vary on a publicly cached response mixes answers between users, so I check it through a real cache. I check security headers on errors too, and through the gateway users go through.