CORS policies for secure browser-based APIs

Browser-based applications often call APIs hosted on another domain, and JavaScript may be unable to read the response even when the request reaches the server. CORS—short for Cross-Origin Resource Sharing—is the browser mechanism that indicates whether a page may access a cross-origin response. It works alongside, rather than replacing, authentication, authorisation, input validation and the security controls expected of Australian organisations.

The distinction matters in the Australian market, where online retailers, SaaS platforms and customer-service products connect hosted storefronts, payment providers, accounting tools and parcel services. A dashboard used by a team in Brisbane may load data from an API operated elsewhere, while the same API serves mobile apps and native systems in Sydney or Melbourne. Consistent cross-origin rules give those integrations a predictable path without exposing every API to unrestricted browser access.

What CORS actually controls

An origin is the combination of scheme, host and port. https://app.example.com.au and https://api.example.com.au have different origins, as do http://localhost:3000 and https://localhost:3000. The browser compares these values when a page makes a request. CORS headers form a negotiated permission list: the server says which requesting origin may receive the response, and the browser enforces that decision for scripts.

The same-origin policy normally stops code running on one origin from reading data on another. A simple cross-origin request may still be sent and may still change data on the server; if the response lacks the required CORS permission, JavaScript cannot inspect it. That is why CORS cannot act as a substitute for server-side authorisation. Native applications, command-line tools and server-to-server jobs do not enforce the browser policy, so API authentication and authorisation must stand on their own.

Common response headers include Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Access-Control-Allow-Credentials and Access-Control-Expose-Headers. The first identifies the permitted origin. The methods and headers headers govern preflight approval, credentials determine whether browser credentials can accompany a request, and expose-headers lists otherwise hidden response headers that scripts may read. A fixed public asset can sometimes use *; credentialed and sensitive responses need an explicit origin.

Designing a safe origin allow-list

Start with the smallest practical set of exact origins that need browser access. Keep schemes and ports precise, include separate development hosts, and decide whether local tools such as http://localhost:5173 are authorised. Avoid accepting any origin beginning with a trusted string because https://app.example.com.au.evil.test would satisfy a careless prefix test. If several subdomains require access, enumerate them or use a tightly controlled domain rule that has been reviewed for takeover and spoofing risks.

A small Express middleware can express the basic policy. This example assumes browser requests may send an authenticated cookie; omit the credentials header when that is not required and keep CORS middleware scoped to the routes that need it.

const allowedOrigins = new Set([
  "https://portal.example.com.au",
  "https://admin.example.com.au",
]);

app.use((req, res, next) => {
  const origin = req.headers.origin;

  if (origin && allowedOrigins.has(origin)) {
    res.set("Access-Control-Allow-Origin", origin);
    res.set("Access-Control-Allow-Credentials", "true");
    res.vary("Origin");
  }

  if (req.method === "OPTIONS") {
    res.set("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE");
    res.set("Access-Control-Allow-Headers", "Content-Type,Authorization");
    return res.status(204).end();
  }

  next();
});

Store the list in validated configuration rather than duplicating it across handlers. A mismatch caused by a trailing slash, an omitted port or http versus https is common. Add Vary: Origin whenever the allowed value changes by request, because a shared cache must not serve one origin’s approval header to another. Review the list whenever teams acquire a new customer portal, administration console or integration.

Preflight, credentials and API responses

Browsers send an OPTIONS preflight before certain cross-origin requests. A request using Content-Type: application/json, an Authorization header, PUT or DELETE will usually trigger one. The browser first asks whether the requested method and headers are permitted; it sends the real request only if the preflight is acceptable. The response should have a successful status and include the allowed origin, methods and any requested headers.

For a credentialed flow, the actual response must contain both Access-Control-Allow-Origin: https://portal.example.com.au and Access-Control-Allow-Credentials: true. The wildcard origin is invalid in that combination. Cookies, HTTP authentication entries and client certificates are credential types, so a public API and an account-specific API often need separate policies. Cookie authentication also requires ordinary defences such as SameSite cookies, secure session handling and CSRF protection where the action is state-changing.

Preflight answers can be cached with Access-Control-Max-Age, but a short, controlled value reduces the impact of a mistaken permission. Actual responses and error responses need the relevant allow-origin header as well; otherwise a successful API call can appear to fail in the browser because its error body is inaccessible. Use Access-Control-Expose-Headers only for headers scripts genuinely need, such as a pagination link or request identifier, rather than exposing every server header by default.

Testing CORS in real user environments

Test with real browser requests, not only curl. A command such as curl -H "Origin: ..." is useful for inspecting headers, but it will not reproduce the browser’s enforcement. Use browser developer tools to inspect both OPTIONS and the eventual request, then automate checks with a tool such as Playwright. The matrix should include an approved origin, a plausible typo, an unapproved subdomain, an attacker-controlled origin and a request containing credentials.

Australian conditions add useful edge cases. Commuters in Sydney and Melbourne often move between mobile broadband, station Wi-Fi and congested café connections, while regional users may rely on variable satellite or fixed-wireless service. Such network changes can make an unrelated timeout look like a CORS failure, so logs should separate DNS, connection, preflight and application errors. Tests should also cover current Chrome, Edge, Firefox and Safari releases on common mobile devices rather than assuming desktop behaviour represents every customer.

A local development proxy can remove browser restrictions during coding, but it can also conceal a broken production policy. Run the integration against the deployed gateway and origin at least once before release. Australian online retailers commonly connect independent payment, shipping and accounting services, and each vendor may add its own callback origins. Keep a current inventory of those browser-facing integrations, check them after gateway changes, and verify that CDN or edge caching preserves the correct Vary behaviour across Australian delivery points.

Security, privacy and ongoing operations

CORS limits one form of cross-origin script access; it does not encrypt data in transit, stop a user from calling an endpoint directly, or determine whether collected information has a lawful purpose. For organisations covered by the Privacy Act 1988, the Australian Privacy Principles still govern collection, use, disclosure and security. A permissive CORS policy cannot justify collecting more personal information than required, while a restrictive policy cannot substitute for access controls, encryption, retention rules and breach-response processes. State and territory privacy regimes may also apply to particular health information.

Treat the origin policy as security-sensitive configuration. Log rejected origins without retaining unnecessary personal information, alert on unexpected bursts of preflight failures, and require code review for changes to allowed hosts. Authentication tokens should have narrow scopes and short lifetimes, and APIs should verify permissions on every protected operation. This prevents a browser policy from becoming the only barrier between an unauthorised caller and Australian customer, employee or supplier records.

Documentation should describe which applications use each API, which origins are approved, whether credentials are expected and who owns each integration. Customer-service platforms can expose more surface area than teams first realise; guidance for self-service help portals is useful when mapping user-facing pages to the APIs behind them. With exact origin controls, correctly handled preflights, credential-aware responses and production tests tied to Australian operating conditions, CORS becomes a deliberate API contract rather than a collection of emergency header changes.