Skip to the content
Documentation
Help Start
Reading in:
  • German: 9,212 of 9,212 pages
About the help in other languages
All help pages

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…

Download as PDF

Address: https://doc.exponential.earth/exphelp/viewer/headless/cors-rate-limits-and-shield.md

On this page

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-After
php 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

  1. The order of the checks
  2. CORS
  3. Exposing the headers a client needs
  4. Credentials and cookies
  5. Rate limits
  6. The request shield
  7. Rules for API clients
  8. Behind a proxy or a CDN
  9. Troubleshooting
  10. 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 errors

A refusal at any step is final for that request. The client sees which step refused by the answer:

AnswerRefused 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 bodythe request shield
204 / 403 to an OPTIONS with OriginCORS
401 {"error":"invalid_token"}, 403 insufficient_scope, 429 {"error":"rate_limited"}the credential check
429 with a GraphQL body, extensions.code RATE_LIMITEDthe 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 Origin is in AllowedOrigins[] carries Access-Control-Allow-Origin with that origin (never * when credentials are allowed), Access-Control-Allow-Credentials: true when AllowCredentials is enabled, and Access-Control-Expose-Headers when ExposedHeaders[] lists any.
  • A request from another origin, or without Origin, gets no Access-Control-* header.
  • Every answer carries Vary: Origin, so a shared cache never serves one origin's answer to another.
  • A preflight (OPTIONS with Origin and Access-Control-Request-Method) is answered by the REST layer and never runs the request: 204 with Access-Control-Allow-Methods, Access-Control-Allow-Headers and Access-Control-Max-Age when the origin, the method and every requested header are allowed; 403 without any Access-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-ID

Browsers 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:

HeaderWho reads it
X-Exponential-Cache-Tagsthe SDK's cacheTags, any tag-based cache
X-GraphQL-Schemathe SDK's schemaHash, type checks in builds
X-GraphQL-Cachethe SDK's cacheState, monitoring
X-Request-Iderror reports
ETagyour own If-None-Match handling
X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, Retry-Afterthe 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).

IdentityLimitDefault per RateLimitWindow (60 s)
a personal API key (by key)RateLimit600
a public read key (by key, every visitor together)RateLimitPublicKey3000
a signed-in user with an OAuth token or a session (by user)RateLimit600
anonymous (by IP address)RateLimitAnonymous120
the consolenone

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

ClientTypical loadSuggested
SSR front end with persisted queries, one keya few requests per page view, most HITRateLimit = expected peak per minute × 2; consider a public read key for its own budget
static build walking 20 000 items, 100 per request200 requests in a few minutesdefault limits suffice; the SDK honors Retry-After
search indexer on webhooksone request per eventdefault
browser SPA, anonymousa few requests per visitor per minutedefault RateLimitAnonymous; make sure the address is the visitor's, not a proxy's
load testthousands per minutea 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 unless retryMutations: true).
  • Watch X-RateLimit-Remaining and slow down before 0.
  • 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 samePOST, 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   429
  • challenge-exempt /api/**: never the browser check there; a client past its budget gets 429 with Retry-After instead, 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-origin POSTs 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 no Origin, and the shield's missing check default then sends them the browser check (set post-origin same missing allow or exempt the API as shown).
  • A partner's server with a fixed address can be exempted from the budgets: exempt 203.0.113.10.
  • expect lines 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-For only when it comes from your proxy; otherwise every visitor shares the proxy's address and its budget.
  • Authorization must reach PHP. Some setups (Apache with FastCGI, container images) drop it unless configured to pass it on; a key that "does nothing" (currentUser { signedInBy } answers anonymous) 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

SymptomCauseFix
browser: "No 'Access-Control-Allow-Origin' header"CORS off, or the origin is not listed exactlyCors=enabled, the exact origin; clear the INI cache
preflight 403a requested header or method not allowedadd it to AllowedHeaders[]/AllowedMethods[] (see the browser's Access-Control-Request-Headers)
works in curl, not in the browserCORS (curl ignores it)as above
the SDK's cacheTags empty in the browserheader not exposedExposedHeaders[]=X-Exponential-Cache-Tags
429 with Request-Shield-Challengethe shield's browser check on /api/challenge-exempt /api/**
403 on cross-origin POSTthe shield's post-origin samepost-origin except /api/**
429 RATE_LIMITED for all visitors at oncethe anonymous limit counts the proxy's addresstrusted proxies
429 {"error":"rate_limited"} with a keyrest.ini RateLimitPerMinuteraise it or set 0
a key is ignored (anonymous)Authorization not passed to PHPpass the header through the web server

Settings

SettingDefaultMeaning
rest.ini [CorsSettings] Corsdisabled
AllowedOrigins[]noneexact origins; * only without credentials
AllowedMethods[]GET POST PUT PATCH DELETEmethods a preflight may ask for
AllowedHeaders[]Authorization Content-Type Accept Accept-Language X-Siteaccessheaders a preflight may ask for
ExposedHeaders[]noneheaders a script may read
MaxAge600seconds a browser keeps a preflight; 0 none
AllowCredentialsdisabledcookies on cross-origin requests
graphql.ini [GraphQLSettings] RateLimit / RateLimitAnonymous / RateLimitPublicKey / RateLimitWindow600 / 120 / 3000 / 60
rest.ini [ApiKeySettings] RateLimitPerMinute120per key, APCu
request shield rulesexponential.rules + the site's filesee the extension's reference

Something wrong on this page? Report an error

Documentation license

This documentation is free documentation, licensed under the GNU Free Documentation License 1.3 or later.

Exponential Copyright © 1998-2026 Exponential Foundation and 7x