CORS, rate limits and the request shield for API clients
What this is. The three things in front of the GraphQL API that can refuse a client before or besides GraphQL itself: cross-origin rules for browsers (CORS), the rate limits of the API and of personal API keys, and the request shield, the small web application firewall that decides every request before the kernel.
When to use it. When a browser on another host calls the API; when a client gets 403, 429 or a browser check
it does not expect; when you size limits for a front end or a build that sends thousands of requests.
Quick example: a front end at https://shop.example.com calls the API of https://www.example.com.
# settings/siteaccess/site/rest.ini.append.php (or settings/override/rest.ini.append.php for every siteaccess)
[CorsSettings]
Cors=enabled
AllowedOrigins[]
AllowedOrigins[]=https://shop.example.com
AllowedOrigins[]=http://localhost:3000
ExposedHeaders[]
ExposedHeaders[]=X-Exponential-Cache-Tags
ExposedHeaders[]=X-GraphQL-Schema
ExposedHeaders[]=X-GraphQL-Cache
ExposedHeaders[]=X-Request-Id
ExposedHeaders[]=ETag
ExposedHeaders[]=X-RateLimit-Limit
ExposedHeaders[]=X-RateLimit-Remaining
ExposedHeaders[]=X-RateLimit-Reset
ExposedHeaders[]=Retry-Afterphp bin/php/ezcache.php --clear-tag=ini --allow-root-user
curl -s -i -X OPTIONS https://www.example.com/api/graphql -H 'Origin: https://shop.example.com' \
-H 'Access-Control-Request-Method: POST' -H 'Access-Control-Request-Headers: content-type,authorization' | head -12
# HTTP/1.1 204 No Content
# Access-Control-Allow-Origin: https://shop.example.com
# Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE
# Access-Control-Allow-Headers: Authorization, Content-Type, Accept, Accept-Language, X-Siteaccess
# Access-Control-Max-Age: 600
# Vary: Origin./console exp:graphql:enable --siteaccess=site --origin=https://shop.example.com --apply writes the origin for you.
Contents
- The order of the checks
- CORS
- Exposing the headers a client needs
- Credentials and cookies
- Rate limits
- The request shield
- Rules for API clients
- Behind a proxy or a CDN
- Troubleshooting
- Settings
The order of the checks
request ─► request shield (methods, paths, budgets, browser check, origin of forms) 403 / 405 / 429
─► early answer of the response cache (persisted queries; counts the rate limit) 200 / 304 / 429
─► REST kernel: siteaccess, CORS (preflight answered here) 204 / 403
─► credential (API key: its own per-minute limit) 401 / 403 / 429
─► GraphQL rate limit (key, user or address) 429 RATE_LIMITED
─► GraphQL limits (length, depth, complexity), policies 200 with errorsA refusal at any step is final for that request. The client sees which step refused by the answer:
| Answer | Refused by |
|---|---|
429 with header Request-Shield-Challenge (JSON body) | the request shield's browser check |
403 / 405 with X-RS (when debug-header is on) or an HTML/plain body | the request shield |
204 / 403 to an OPTIONS with Origin | CORS |
401 {"error":"invalid_token"}, 403 insufficient_scope, 429 {"error":"rate_limited"} | the credential check |
429 with a GraphQL body, extensions.code RATE_LIMITED | the GraphQL rate limit |
CORS
A browser lets a page of one origin read an answer of another only when the answer allows it. The REST layer (every
/api/... route, /api/graphql included) answers CORS by rest.ini [CorsSettings], off by default.
While it is off nothing is added: no Access-Control-* header, and an OPTIONS request goes to the router as
before. A browser on another origin then cannot read any answer. Server-side clients (Node.js, PHP, curl) do not care
about CORS at all.
While it is on:
- An answer to a request whose
Originis inAllowedOrigins[]carriesAccess-Control-Allow-Originwith that origin (never*when credentials are allowed),Access-Control-Allow-Credentials: truewhenAllowCredentialsis enabled, andAccess-Control-Expose-HeaderswhenExposedHeaders[]lists any. - A request from another origin, or without
Origin, gets noAccess-Control-*header. - Every answer carries
Vary: Origin, so a shared cache never serves one origin's answer to another. - A preflight (
OPTIONSwithOriginandAccess-Control-Request-Method) is answered by the REST layer and never runs the request:204withAccess-Control-Allow-Methods,Access-Control-Allow-HeadersandAccess-Control-Max-Agewhen the origin, the method and every requested header are allowed;403without anyAccess-Control-*header otherwise.
Origins are written exactly as the browser sends them: scheme, host, and the port when it is not the default; no
path, no trailing slash. https://shop.example.com and https://www.shop.example.com are two origins; so are
http://localhost:3000 and http://localhost:5173. null is never accepted. * (any origin) is accepted only while
AllowCredentials is disabled, and is rarely right: it lets every website read what anonymous requests read, which
is public anyway, but also lets any website spend your visitors' anonymous rate limit.
When a browser sends a preflight. Every POST with Content-Type: application/json and every request with an
Authorization header. A GET of a persisted query without custom headers sends none: the cheapest cross-origin
call there is.
Headers a preflight may ask for (AllowedHeaders[], compared without case): Authorization, Content-Type,
Accept, Accept-Language, X-Siteaccess by default. A client that sends If-None-Match, Last-Event-ID or
X-CSRF-Token across origins needs them added:
AllowedHeaders[]=If-None-Match
AllowedHeaders[]=Last-Event-IDBrowsers add If-None-Match to their own cache revalidations without a preflight; only a script that sets it itself
needs it listed. Libraries that add headers of their own (tracing headers such as traceparent, sentry-trace) need
those listed too, or the preflight is refused.
Per siteaccess. CORS settings follow the siteaccess the request is answered in, so a public siteaccess can allow the shop's origin while the editing siteaccess allows none.
Exposing the headers a client needs
Without ExposedHeaders[], a script on another origin reads only the CORS-safelisted headers (Content-Type,
Cache-Control ...): it cannot read the cache tags, the schema hash, the rate limit or the ETag. List what your
client reads:
| Header | Who reads it |
|---|---|
X-Exponential-Cache-Tags | the SDK's cacheTags, any tag-based cache |
X-GraphQL-Schema | the SDK's schemaHash, type checks in builds |
X-GraphQL-Cache | the SDK's cacheState, monitoring |
X-Request-Id | error reports |
ETag | your own If-None-Match handling |
X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, Retry-After | the SDK's rateLimit and retries |
Credentials and cookies
Leave AllowCredentials=disabled (the default) for clients that send a key or token in the Authorization header:
that is the usual case, and it needs no cookies. AllowCredentials=enabled makes browsers send and keep cookies on
cross-origin requests, which means the session of a signed-in editor: then the origins must be exact (no *), and
mutations with a session still need the form token (X-CSRF-Token). Use it only for an editing tool on another
origin that relies on the editor's session.
Rate limits
Two independent limits can apply to an API request.
The GraphQL rate limit (graphql.ini)
A fixed window per identity, counted in small files under var/cache/graphql/rate/ with an exclusive lock, so every
PHP-FPM and Velocity worker of one server counts the same requests (no database, no shared memory).
| Identity | Limit | Default per RateLimitWindow (60 s) |
|---|---|---|
| a personal API key (by key) | RateLimit | 600 |
| a public read key (by key, every visitor together) | RateLimitPublicKey | 3000 |
| a signed-in user with an OAuth token or a session (by user) | RateLimit | 600 |
| anonymous (by IP address) | RateLimitAnonymous | 120 |
| the console | none |
0 switches a limit off. Early answers of the response cache are counted too. Every answer carries:
X-RateLimit-Limit: 120
X-RateLimit-Remaining: 117
X-RateLimit-Reset: 36(Reset: seconds until the window ends.) Over the limit: 429 with Retry-After and
{"errors":[{"message":"Too many requests: at most 120 in 60 seconds. Try again in 36 seconds.","extensions":{"code":"RATE_LIMITED"}}]}The request costs nothing beyond the count: no schema is built and no query runs.
The key limit of the REST layer (rest.ini)
[ApiKeySettings] RateLimitPerMinute (120) limits every personal API key per minute, counted in APCu (per PHP-FPM
pool or per Velocity server; without APCu it is not enforced, and oauthadmin/keys says so). Over it: 429
{"error":"rate_limited"} with Retry-After until the minute ends. Early answers of the GraphQL response cache never
reach this check. For a public read key in front of a busy site, raise it or set it to 0 and rely on
RateLimitPublicKey.
Sizing
| Client | Typical load | Suggested |
|---|---|---|
| SSR front end with persisted queries, one key | a few requests per page view, most HIT | RateLimit = expected peak per minute × 2; consider a public read key for its own budget |
| static build walking 20 000 items, 100 per request | 200 requests in a few minutes | default limits suffice; the SDK honors Retry-After |
| search indexer on webhooks | one request per event | default |
| browser SPA, anonymous | a few requests per visitor per minute | default RateLimitAnonymous; make sure the address is the visitor's, not a proxy's |
| load test | thousands per minute | a dedicated key with RateLimit=0 on a test siteaccess only |
Clients that behave
- Honor
Retry-After(the SDK does:retry: { attempts: 3, baseDelayMs: 250, maxDelayMs: 10000 }, never for mutations unlessretryMutations: true). - Watch
X-RateLimit-Remainingand slow down before0. - Batch: one query with aliases instead of ten requests; cursor pages of 100 instead of 25.
- Cache: persisted queries,
ETags, your framework's cache.
The request shield
The extension exp_request_shield (request-shield, a small web application firewall) decides every request before
the kernel: allowed methods per path, path rules, per-visitor budgets, a JavaScript browser check for suspicious
traffic, the origin of form posts, known crawlers, and lists of addresses. It is active only when its hook is in
config.php; see The request shield and
Setting up the request shield. Its full rule reference is in the extension:
exp_request_shield, doc/reference.md.
What matters for API clients:
Shipped rule (exponential.rules) | Effect on /api/** |
|---|---|
[EXP-API] api-path **/ezjscore/** /api/** | a browser check there comes as JSON: 429 with the header Request-Shield-Challenge, never an HTML page |
[EXP-POST] allow POST ... /api/** | POST is allowed on the API (other paths without a form answer 405) |
[EXP-ORIGIN] post-origin same | POST, PUT, PATCH, DELETE only from the website's own pages: an Origin (or Referer) of another website is 403; neither header: the browser check |
[EXP-PACE] limit pages 300/min challenge-at 120 ... | a visitor's pace: past 120 requests a minute the browser check |
A program runs no JavaScript and cannot pass a browser check. The SDK reports it as ExponentialShieldChallengeError
(a 429 with Request-Shield-Challenge).
Rules for API clients
Add rules for the API to the site's rules file (settings/request-shield/request-shield.rules, or the file of
EXP_REQUEST_SHIELD_RULES). The rules come from the extension's cookbook ("The REST API") and keep the shield's
protection while letting programs through:
method GET HEAD POST OPTIONS PUT PATCH DELETE
[SITE-REST-METHODS] allow PUT PATCH DELETE /api/** # the REST API changes content with PUT, PATCH and DELETE
[SITE-REST-NOCHECK] challenge-exempt /api/** # API clients run no JavaScript: never the check, only the pause
[SITE-REST-BUDGET] limit api 300/min at /api/** # the API: 300 requests a minute per client, then 429
[SITE-API-ORIGIN] post-origin except /api/** # browsers of allowed origins and programs post to the API
expect POST /api/graphql header Origin:https://shop.example.com answered
expect GET /api/graphql?id=articles times 300 answered
expect GET /api/graphql?id=articles times 301 429challenge-exempt /api/**: never the browser check there; a client past its budget gets429withRetry-Afterinstead, which the SDK honors.limit api 300/min at /api/**: a budget of its own for the API, per client address. Keep it above the API's own rate limits for the clients you expect, or it refuses first.post-origin except /api/**: cross-originPOSTs to the API are then decided by CORS and the credentials, not by the form-origin rule. Leave it out when only same-origin pages and server-side programs call the API: programs send noOrigin, and the shield'smissing checkdefault then sends them the browser check (setpost-origin same missing allowor exempt the API as shown).- A partner's server with a fixed address can be exempted from the budgets:
exempt 203.0.113.10. expectlines are tests the shield checks when the rules are loaded: keep them, they document the intent.
Check the rules before you rely on them, with the shield's command line (extension/exp_request_shield/bin/request-shield, see
its doc/cli.md), and watch Setup > Request shield for refusals on /api/.
Behind a proxy or a CDN
- The client's address. The anonymous rate limit, the subscription limit per address and the shield's budgets
count by IP address. Behind a reverse proxy or a CDN, configure the trusted proxies
(trusted proxies) so the kernel reads the client's address from
X-Forwarded-Foronly when it comes from your proxy; otherwise every visitor shares the proxy's address and its budget. Authorizationmust reach PHP. Some setups (Apache with FastCGI, container images) drop it unless configured to pass it on; a key that "does nothing" (currentUser { signedInBy }answersanonymous) is the symptom.- Streams. Subscriptions need unbuffered proxies with long read timeouts (see Events, webhooks and subscriptions, "Subscriptions").
- Caching of API answers at a CDN: see Cache tags and invalidation, "CDN purging".
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| browser: "No 'Access-Control-Allow-Origin' header" | CORS off, or the origin is not listed exactly | Cors=enabled, the exact origin; clear the INI cache |
preflight 403 | a requested header or method not allowed | add it to AllowedHeaders[]/AllowedMethods[] (see the browser's Access-Control-Request-Headers) |
| works in curl, not in the browser | CORS (curl ignores it) | as above |
the SDK's cacheTags empty in the browser | header not exposed | ExposedHeaders[]=X-Exponential-Cache-Tags |
429 with Request-Shield-Challenge | the shield's browser check on /api/ | challenge-exempt /api/** |
403 on cross-origin POST | the shield's post-origin same | post-origin except /api/** |
429 RATE_LIMITED for all visitors at once | the anonymous limit counts the proxy's address | trusted proxies |
429 {"error":"rate_limited"} with a key | rest.ini RateLimitPerMinute | raise it or set 0 |
| a key is ignored (anonymous) | Authorization not passed to PHP | pass the header through the web server |
Settings
| Setting | Default | Meaning |
|---|---|---|
rest.ini [CorsSettings] Cors | disabled | |
AllowedOrigins[] | none | exact origins; * only without credentials |
AllowedMethods[] | GET POST PUT PATCH DELETE | methods a preflight may ask for |
AllowedHeaders[] | Authorization Content-Type Accept Accept-Language X-Siteaccess | headers a preflight may ask for |
ExposedHeaders[] | none | headers a script may read |
MaxAge | 600 | seconds a browser keeps a preflight; 0 none |
AllowCredentials | disabled | cookies on cross-origin requests |
graphql.ini [GraphQLSettings] RateLimit / RateLimitAnonymous / RateLimitPublicKey / RateLimitWindow | 600 / 120 / 3000 / 60 | |
rest.ini [ApiKeySettings] RateLimitPerMinute | 120 | per key, APCu |
| request shield rules | exponential.rules + the site's file | see the extension's reference |