← Back to blog

How to Add CORS Headers to Your Server (With Examples)

November 4, 2026
How to Add CORS Headers to Your Server (With Examples)

You add CORS headers on the server that owns the data, not in the browser and not in the front-end code that makes the request. The server's response needs an Access-Control-Allow-Origin header naming the site allowed to read it. Requests that trigger a preflight also need Access-Control-Allow-Methods and Access-Control-Allow-Headers. Below you will find what each header does, config you can adapt for common stacks, and a checklist for the errors that remain.

Pingfloat
Check Your Site’s Other Essentials
After configuring CORS, use Pingfloat’s website uptime monitoring, SSL checks, and network diagnostics to review other aspects of your site’s health.
Explore Pingfloat tools

TL;DR

  • CORS headers are set on the response of the server you are calling. Changing your front-end code cannot fix a missing header.
  • Start with one header: Access-Control-Allow-Origin set to the exact origin of your front end, such as https://app.example.com.
  • Requests with custom headers or methods like PUT and DELETE trigger a preflight OPTIONS request, which your server must answer with the right headers.
  • Never combine a wildcard origin with credentials, and never reflect any origin blindly.
  • After deploying, inspect the real response headers to confirm what the browser sees.

Table of Contents

What CORS headers actually do

Browsers apply the same-origin policy: a script on one origin cannot freely read responses from another. CORS is an HTTP-header-based mechanism that lets a server name other origins from which a browser should permit loading resources. The headers do not protect your API from being called. They tell the browser whether it may hand the response to the script that asked.

Two consequences follow, and they explain most of the confusion in forum threads:

  1. The fix always lives on the server that sends the response. If you do not control that server, you cannot add the header. You would need a proxy or a change by whoever runs the API.
  2. An origin is the combination of scheme, host and port. http://localhost:3000 and http://localhost:5173 are different origins, and so are http and https versions of the same host.

For a deeper walk through every header, see our guide on what each CORS header does and how to fix errors.

The response headers you need

Most setups need only a handful of headers. The table summarizes them.

HeaderWhat it controlsTypical value
Access-Control-Allow-OriginWhich origin may read the responsehttps://app.example.com
Access-Control-Allow-MethodsMethods allowed on a preflighted requestGET, POST, PUT, DELETE
Access-Control-Allow-HeadersRequest headers allowed on a preflighted requestContent-Type, Authorization
Access-Control-Allow-CredentialsWhether cookies or auth data may be includedtrue (only when needed)
Access-Control-Max-AgeHow long the browser may cache the preflight result600
VaryTells caches the response depends on the request originOrigin

Per MDN, a response uses Access-Control-Allow-Origin to permit an origin, while for a preflight request Access-Control-Allow-Methods and Access-Control-Allow-Headers specify the allowed methods and request headers (MDN). For requests without credentials, Access-Control-Allow-Origin can be a single origin or the * wildcard (MDN).

Pick the narrowest value that works

The wildcard * is fine for a public, read-only resource such as an open dataset or a font file. For an API that serves your own app, name the origin. If more than one site needs access, keep an allow list on the server, compare the incoming Origin header against it, and echo back only a match. Add Vary: Origin when the value changes per request, so caches do not serve one site's answer to another. For caching details, see our Cache-Control headers guide.

Avoid the literal value null. MDN warns that hostile documents with a null origin may be granted access, so it should not be used as an allowed origin.

Pick the narrowest value that works

How to add CORS headers on common stacks

The snippets below use https://app.example.com as the front-end origin. Replace it with yours, and keep the list as short as you can.

Express (Node.js)

You can set headers by hand in a middleware, which makes the behavior easy to see:

const allowed = ['https://app.example.com'];

app.use((req, res, next) => {
  const origin = req.headers.origin;
  if (allowed.includes(origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin);
    res.setHeader('Vary', 'Origin');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  }
  if (req.method === 'OPTIONS') {
    return res.sendStatus(204);
  }
  next();
});

Place this before your routes, so the preflight is answered before any authentication or routing logic rejects it. Many teams use the popular cors package instead, which wraps the same logic in configuration options.

Nginx

In a location block that proxies or serves your API:

location /api/ {
    add_header 'Access-Control-Allow-Origin' 'https://app.example.com' always;
    add_header 'Vary' 'Origin' always;

    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' 'https://app.example.com' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
        add_header 'Access-Control-Max-Age' 600;
        return 204;
    }

    proxy_pass http://backend;
}

The always flag matters: without it, Nginx omits the header on error responses, and the browser then reports a CORS failure that hides the real 4xx or 5xx status. The headers are repeated inside the if block because add_header directives in an inner block replace those from the outer one.

Apache

With mod_headers enabled, in your virtual host or .htaccess:

Header always set Access-Control-Allow-Origin "https://app.example.com"
Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "Content-Type, Authorization"
Header merge Vary Origin

Apache will still pass OPTIONS requests to your application unless you handle them. If the app rejects them, add a rewrite rule that returns 204 for OPTIONS.

ASP.NET Core

Microsoft documents that CORS in ASP.NET Core can be enabled with middleware, endpoint routing, or the EnableCors attribute by configuring a policy with allowed origins. A minimal middleware setup looks like this:

builder.Services.AddCors(options =>
{
    options.AddPolicy("AppPolicy", policy =>
        policy.WithOrigins("https://app.example.com")
              .WithMethods("GET", "POST", "PUT", "DELETE")
              .WithHeaders("Content-Type", "Authorization"));
});

var app = builder.Build();
app.UseCors("AppPolicy");

Call UseCors before the endpoints it should protect, and after routing, as the Microsoft documentation describes.

Hosting platforms and CDNs

Managed hosts often expose CORS as a setting rather than code: a toggle, a rules file, or a response header policy on the CDN. The principle is the same. The header must appear on the response from the origin you are calling, and you should verify it after deployment, because a CDN can cache an earlier response without the header.

Preflight requests: the part that trips people up

Not every request triggers one. A preflight is an OPTIONS request the browser sends first when the actual request does not meet the conditions for a simple request, for example because it uses a method other than GET, HEAD or POST, or sends non-safelisted headers. A JSON POST with an Authorization header or a PUT to your API will usually trigger one.

Your server must answer that OPTIONS request with CORS headers that approve the origin, methods and request headers. Three practical rules:

  • Return success without redirects. A preflight should get a 204 No Content response without redirecting, according to enable-cors.org. A redirect from http to https or from a missing trailing slash is a classic cause of failure.
  • Do not require authentication on OPTIONS. Browsers do not send your credentials on the preflight, so an auth check that returns 401 or 403 fails every time.
  • Cache the result. Servers can include the Access-Control-Max-Age header so the browser reuses the preflight result and sends fewer repeat requests.

If your API returns custom headers you want the front-end script to read, expose them with Access-Control-Expose-Headers; by default scripts see only a small safelisted set.

Requests with credentials

If your front end sends cookies or HTTP authentication, the request must opt in (credentials: 'include' in fetch) and the server must respond with Access-Control-Allow-Credentials: true. In that case the origin must be a specific value, not *. Microsoft's documentation states that configuring a service with both AllowAnyOrigin and AllowCredentials is insecure and results in an invalid CORS response. The same pairing fails in every other stack.

For the same reason, avoid the shortcut of echoing back whatever Origin arrives together with credentials enabled. That grants every website on the internet access to your users' authenticated data. Check the origin against your allow list first.

Requests with credentials

Troubleshooting: when the headers are set and it still fails

Work through this list in order. Most CORS errors come from one of these.

  1. Read the console message. Chrome and Firefox usually say which header is missing or which value did not match. That message tells you whether to fix the origin, the methods or the headers.
  2. Check the exact origin. Port differences make origins different, and a trailing slash or a URL mismatch can cause issues. The allowed origin is https://app.example.com, with no path and no trailing slash.
  3. Look for duplicate headers. If both your app and your proxy add Access-Control-Allow-Origin, the browser sees two values and rejects the response. Set it in one layer only. This is among the common troubleshooting steps along with handling OPTIONS and sending Vary: Origin.
  4. Confirm error responses carry the headers. A 500 from your server without CORS headers shows up in the browser as a CORS error. Fix the server error first; our reference on the 500 Internal Server Error covers common causes.
  5. Match the request headers to the allow list. If the preflight asks for X-Api-Key and your Access-Control-Allow-Headers omits it, the actual request never goes out.
  6. Check for a wildcard with credentials. See the section above.
  7. Bypass stale caches. A CDN or browser may be serving an older response from before you added the headers.

Why the "disable security" tricks are not a fix

Browser extensions and flags that disable CORS checks, or DevTools header overrides, are useful for a quick experiment on your own machine. They change what your browser does, not what your server sends, so your users will still see the error. Treat them as a way to confirm a diagnosis, then fix the server.

Verify what the browser actually receives

Guessing wastes time when you can read the headers. Open the Network panel, select the failing request, and look at the response headers, including the preflight OPTIONS entry. You can also check any public URL with our Response Headers Inspector to see whether Access-Control-Allow-Origin, Vary and related headers are present in the response. If you want a broader view of how headers behave across protocol versions, read about debugging HTTP/2 and HTTP/3 headers.

CORS is one part of your header configuration. Once it works, review the rest in our security headers checklist so that opening one door does not leave others unlocked.

Our perspective

Most CORS pain comes from the same mismatch: people look for the fix where they see the error, in the browser, while the fix lives on the server. We build Pingfloat's tools around that idea. When something breaks, you should be able to see the real response, headers included, in seconds and without installing anything.

Our advice is to be boring with CORS. Name one origin, answer the preflight with a clean 204, set the header in a single layer, and check the result on a live URL. Reaching for a wildcard because it makes the error disappear is how small shortcuts become security reviews later.

This is also why we keep our core tools free and open without an account. Checking a response header, an SSL certificate or a redirect should be a ten-second task, not a setup project. Pair header checks with uptime monitoring and you catch a broken deployment before your users report it.

Andreas

Check your headers after every deploy

A CORS change can break quietly: a new proxy layer, a CDN rule or a redeploy removes a header, and your front end fails while the server stays up. Pingfloat gives you free tools to catch this. Inspect response headers on any URL, and use the Website Uptime Monitor to keep watch on the endpoints your front end depends on. Signing up unlocks extras such as scheduled monitoring and saved results, and the core tools work without an account. Browse the full set on the Pingfloat home page.

Pingfloat

If you automate checks, the Pingfloat Public API lets you bring the same tooling into your own workflow.

FAQ

Can I add CORS headers from the front-end code?

No. CORS headers are response headers, and the browser trusts only what the server it called sends back. Setting them in your fetch request does nothing useful, and a header like Access-Control-Allow-Origin on a request can even trigger a preflight. If you do not control the API, ask its owner to add your origin or route the call through your own back end.

Is it safe to use Access-Control-Allow-Origin: *?

It is acceptable for public resources that carry no user-specific data, because for requests without credentials the header can be a wildcard. It is not appropriate for authenticated APIs, and it cannot be combined with credentials. For anything private, name the specific origins you trust.

Why do I see a CORS error when the real problem is a 500 or 404?

When the server's error response lacks CORS headers, the browser blocks the script from reading it and reports a CORS failure instead of the status. Make sure your server or proxy adds the headers on error responses too (in Nginx, with the always flag), then read the actual status in the Network panel.

Do I need to handle OPTIONS requests myself?

Usually yes, unless your framework or CORS middleware does it for you. The server needs to answer the preflight OPTIONS request with the allowed origin, methods and headers, and return a 204 without a redirect. If authentication middleware runs first and rejects the request, the preflight fails.

How do I allow multiple origins?

The header accepts only one origin (or the wildcard), so keep an allow list on the server. Compare the request's Origin value to the list, echo it back only on a match, and add Vary: Origin so caches store a separate response per origin.

Sources