You have built a frontend application using React, connected it to a Laravel or Node.js backend, and everything seems ready.
You open the application, trigger an API request, and suddenly your browser console displays an error:
Access to fetch at 'https://api.example.com/users'
from origin 'https://app.example.com'
has been blocked by CORS policy.The API endpoint works when you test it using Postman. The backend is running correctly, and the request URL appears valid.
So why is the browser blocking it?
The answer is usually CORS (Cross-Origin Resource Sharing).
CORS is one of those web development concepts that developers frequently encounter but do not always fully understand. It becomes especially important when frontend applications communicate with APIs hosted on different domains, ports, or protocols.
In this guide, we will explain what CORS is, why browsers enforce it, how preflight requests work, and how to configure CORS correctly in PHP, Laravel, and Node.js applications.
What Is CORS?
CORS stands for Cross-Origin Resource Sharing.
It is a browser security mechanism that allows a server to specify which origins are permitted to access its resources through browser-based cross-origin requests.
In simple terms, CORS tells the browser whether a website is allowed to read a response from another website.
Imagine you have two applications:
Frontend:
https://store.example.comBackend API:
https://api.example.com
The frontend sends a request to the backend API to retrieve product information.
Although both applications belong to the same parent domain, they are considered different origins because their hostnames are different.
The browser applies its same-origin policy and requires the API server to explicitly permit the cross-origin access through appropriate CORS response headers.
For example:
Access-Control-Allow-Origin: https://store.example.comThis header tells the browser that the specified origin is allowed to access the response.
Importantly, CORS is enforced by browsers. It does not prevent server-to-server HTTP requests from being made.
What Is an Origin?
Before understanding CORS, you need to understand what an origin means.
An origin consists of three components:
Scheme (protocol)
Hostname
Port
For example:
https://example.com:443Here:
Scheme: HTTPS
Hostname: example.com
Port: 443
Two URLs have the same origin only when all three components match.
Consider these examples:
URL A | URL B | Same origin? |
|---|---|---|
Yes | ||
No | ||
No | ||
No | ||
Yes | ||
No |
This explains why a React application running on port 3000 may encounter CORS errors when calling a Laravel API running on port 8000.
Even though both applications run on the same computer, their origins are different.
Understanding the Same-Origin Policy
The same-origin policy is a browser security rule that restricts how documents and scripts from one origin interact with resources from another origin.
Without these restrictions, a malicious website could potentially use a visitor's authenticated browser session to access information from another website.
For example, imagine a user is logged into an online banking application.
The user then visits an unrelated malicious website.
Without appropriate browser security protections, scripts on that website could attempt to interact with the banking application using the user's existing browser session.
The same-origin policy helps restrict this kind of cross-origin interaction.
However, modern applications need to communicate with external APIs legitimately.
This is where CORS comes in.
CORS allows servers to explicitly grant cross-origin access instead of allowing every website to access their resources.
How Does CORS Work?
Let's walk through a practical example.
Suppose your frontend application runs at:
https://frontend.example.comYour backend API runs at:
https://api.example.comThe frontend sends an HTTP request:
fetch('https://api.example.com/products')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));The browser sends an HTTP request containing an Origin header:
GET /products HTTP/1.1
Host: api.example.com
Origin: https://frontend.example.comThe backend responds with:
HTTP/1.1 200 OK
Content-Type: application/json
Access-Control-Allow-Origin: https://frontend.example.comBecause the response contains a matching CORS header, the browser allows the frontend JavaScript to access the response.
If the server does not return an appropriate CORS response header, the browser blocks JavaScript from reading the cross-origin response.
An important distinction: the server may still receive and process the request even when the browser refuses to expose the response to JavaScript.
What Is a CORS Preflight Request?
One of the most confusing parts of CORS is the preflight request.
Some cross-origin requests require the browser to send an initial OPTIONS request before sending the actual request.
This is called a preflight request.
The browser uses it to ask the server whether the intended cross-origin request is permitted.
When does a preflight request happen?
Preflight requests are generally required for requests that do not qualify as CORS-safelisted requests.
Common examples include:
Using HTTP methods such as PUT, PATCH, or DELETE.
Sending custom HTTP headers such as Authorization.
Using Content-Type values such as application/json.
Consider this example:
fetch('https://api.example.com/users/10', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
},
body: JSON.stringify({
name: 'John Smith'
})
});Before sending the actual PUT request, the browser may send an OPTIONS request.
Example preflight request
OPTIONS /users/10 HTTP/1.1
Host: api.example.com
Origin: https://frontend.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: authorization, content-typeThe server should respond with the appropriate permissions:
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://frontend.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Max-Age: 3600The browser checks the response.
If the preflight succeeds, it proceeds with the actual PUT request.
If the preflight fails, the browser does not send the actual request.
The Access-Control-Max-Age header tells the browser how long it may cache the preflight permission, subject to browser limits.
Important CORS HTTP Headers
Understanding the common CORS headers makes debugging much easier.
1. Access-Control-Allow-Origin
Specifies which origin can access the resource.
Access-Control-Allow-Origin: https://frontend.example.comFor a public resource that does not require credentialed access, a server may use:
Access-Control-Allow-Origin: *However, wildcard access is not appropriate for every API.
2. Access-Control-Allow-Methods
Specifies which HTTP methods are permitted for cross-origin requests.
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS3. Access-Control-Allow-Headers
Specifies which request headers the browser is permitted to send.
Access-Control-Allow-Headers: Content-Type, Authorization4. Access-Control-Allow-Credentials
Indicates whether the browser may expose the response to JavaScript when the request uses credentials.
Access-Control-Allow-Credentials: trueWhen credentialed access is enabled, the server cannot use * as the allowed origin. It must return a specific permitted origin.
5. Access-Control-Expose-Headers
Specifies which response headers JavaScript can access beyond the CORS-safelisted response headers.
Access-Control-Expose-Headers: X-Request-ID, X-Total-Count6. Access-Control-Max-Age
Controls how long the browser can cache a successful preflight response.
Access-Control-Max-Age: 36007. Vary: Origin
When a server dynamically returns different CORS headers depending on the requesting origin, it should generally include:
Vary: OriginThis helps prevent shared caches from serving a response generated for one origin to another origin.
How to Fix CORS Errors in Laravel
Laravel provides built-in CORS support through its framework configuration.
The configuration is generally managed through:
config/cors.phpA typical configuration might look like this:
return [
'paths' => [
'api/*',
'sanctum/csrf-cookie'
],
'allowed_methods' => [
'GET',
'POST',
'PUT',
'PATCH',
'DELETE',
'OPTIONS'
],
'allowed_origins' => [
'https://frontend.example.com'
],
'allowed_origins_patterns' => [],
'allowed_headers' => [
'Content-Type',
'Authorization',
'X-Requested-With'
],
'exposed_headers' => [],
'max_age' => 3600,
'supports_credentials' => false,
];Adjust the configuration according to your actual application routes and authentication requirements.
After modifying the configuration, clear and rebuild the configuration cache when necessary:
php artisan config:clear
php artisan config:cacheLaravel with cookie-based authentication
If your application uses Laravel Sanctum or another cookie-based authentication approach, CORS configuration requires additional attention.
For credentialed cross-origin requests:
'supports_credentials' => true,Your frontend must also send credentials:
fetch('https://api.example.com/user', {
method: 'GET',
credentials: 'include'
});The backend must return a specific allowed origin rather than *.
Cookie attributes such as SameSite, Secure, and domain configuration also affect whether cookies are sent.
CORS configuration alone does not guarantee that browser cookies will be included.
How to Fix CORS Errors in Node.js and Express
If you are using Node.js with Express, the cors middleware provides a convenient way to configure cross-origin access.
Install the package:
npm install corsImport and configure it:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({
origin: 'https://frontend.example.com',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
app.get('/products', (req, res) => {
res.json({
message: 'Products retrieved successfully'
});
});
app.listen(3000, () => {
console.log('API server running on port 3000');
});The middleware handles the appropriate CORS response headers and preflight requests.
For applications that support multiple frontend origins, use an explicit allowlist and validate each incoming origin before reflecting it in the response.
Do not automatically trust every origin supplied by the request.
How to Fix CORS Errors in Plain PHP
If you are developing a PHP API without a framework, you can add the required response headers manually.
Example:
<?php
$allowedOrigins = [
'https://frontend.example.com',
'https://admin.example.com'
];
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (in_array($origin, $allowedOrigins, true)) {
header("Access-Control-Allow-Origin: $origin");
header('Vary: Origin');
}
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(204);
exit;
}
// Continue with API processing.This example demonstrates a basic origin allowlist and preflight response.
In production, make sure:
Origin validation happens before reflecting the origin.
The preflight response is handled before authentication middleware rejects OPTIONS requests.
CORS headers are included consistently on relevant responses, including errors.
Credential support is explicitly configured if required.
The application does not trust arbitrary origins.
Why Does My API Work in Postman but Fail in the Browser?
This is one of the most common questions developers ask when debugging CORS.
The reason is that Postman and browsers handle cross-origin security differently.
Postman is not subject to the browser's same-origin policy and does not enforce browser CORS restrictions.
Therefore, an API request may succeed in Postman while failing in a browser.
Consider the following situation:
Test | Result |
|---|---|
API request from Postman | Successful |
API request from backend PHP code | Successful |
API request from React application | CORS error |
This does not necessarily mean the API is broken.
It means the browser is not receiving or accepting the required CORS permissions.
When troubleshooting, inspect the browser's Network tab and check both the OPTIONS request and the actual response.
Common CORS Errors and Their Solutions
Error or symptom | Possible cause | Recommended solution |
|---|---|---|
No Access-Control-Allow-Origin header | Missing CORS response header | Configure the allowed origin |
Origin is not allowed | Incorrect origin configuration | Add the exact frontend origin |
Method is not allowed | Missing method permission | Update Access-Control-Allow-Methods |
Request header is not allowed | Missing custom header permission | Update Access-Control-Allow-Headers |
Preflight request fails | OPTIONS request rejected or misconfigured | Handle OPTIONS correctly |
Wildcard not allowed with credentials |
| Return a specific origin |
API works in Postman but not browser | Browser CORS restrictions | Inspect browser Network tab |
Common CORS Misconceptions
There are several misconceptions worth understanding.
1. CORS is an authentication mechanism
Incorrect.
CORS does not authenticate users or authorize API operations.
A server must still implement proper authentication and authorization.
2. Using Access-Control-Allow-Origin: * fixes every CORS issue
Incorrect.
Wildcard access does not work for credentialed browser requests.
It also does not automatically permit every HTTP method or custom request header.
3. CORS errors always mean the backend API is broken
Incorrect.
The API might process the request successfully while the browser refuses to expose its response to frontend JavaScript.
4. Disabling browser security is a proper solution
Incorrect.
Disabling browser security may hide the problem during local testing, but it is not a production solution.
Configure the backend API with the correct CORS policy instead.
5. CORS protects APIs from unauthorized requests
Incorrect.
CORS controls whether browser scripts can read cross-origin responses. It is not a replacement for authentication, authorization, CSRF protection, or server-side input validation.
CORS Security Best Practices
When configuring CORS for production applications, follow these recommendations:
Allow only trusted frontend origins.
Avoid wildcard origins when credentialed requests are required.
Restrict allowed HTTP methods to those your API actually supports.
Allow only the request headers your application needs.
Handle OPTIONS requests correctly.
Keep authentication and authorization independent of CORS.
Review cookie settings when using session-based authentication.
Use HTTPS for production applications.
Return appropriate CORS headers on error responses.
Avoid dynamically reflecting arbitrary origins without validation.
A properly configured CORS policy should provide the access your application needs without granting unnecessary cross-origin permissions.
Final Thoughts
CORS is an essential part of modern browser-based application security.
If you develop frontend applications that communicate with APIs hosted on different origins, understanding CORS will help you troubleshoot problems much faster.
The most important concepts to remember are:
Origins are defined by scheme, hostname, and port.
Browsers enforce the same-origin policy.
CORS allows servers to grant controlled cross-origin access.
Preflight requests use the OPTIONS method to check permissions.
CORS response headers determine whether browser JavaScript can access a response.
CORS does not replace authentication or authorization.
The next time you encounter a CORS error, do not immediately change your frontend code or disable browser security. Inspect the request, check the response headers, and verify the backend's CORS configuration.
Understanding the underlying problem is usually much more effective than applying random configuration changes.
Building APIs or debugging web applications? Explore more practical developer resources and online tools at Agilelogics.com.
Frequently Asked Questions
What does CORS stand for?
CORS stands for Cross-Origin Resource Sharing. It is a browser security mechanism that allows servers to specify which origins can access resources through cross-origin browser requests.
Why am I getting a CORS error?
A CORS error usually occurs when a browser request does not receive the required CORS permissions from the server. Common reasons include an incorrect allowed origin, missing headers, or a failed preflight request.
How do I fix a CORS error?
Configure the backend server to return the appropriate CORS response headers for the requesting origin, HTTP method, and request headers. If credentials are involved, configure them explicitly.
What is a preflight request in CORS?
A preflight request is an HTTP OPTIONS request sent by a browser before certain cross-origin requests. It checks whether the server permits the intended method and request headers.
Why does CORS work in Postman but not in Chrome?
Postman does not enforce browser CORS restrictions. Chrome does. Therefore, an API may work in Postman but fail when called from frontend JavaScript.
Can I disable CORS?
Browsers have development mechanisms for bypassing security restrictions, but disabling browser security is not a proper application fix. Configure the backend CORS policy instead.
Is CORS required for every API?
No. CORS is relevant when browser-based applications make cross-origin requests. Server-to-server API requests are not subject to browser CORS enforcement.
Is CORS the same as CSRF protection?
No. CORS controls cross-origin response access in browsers. CSRF protection addresses unauthorized actions performed using a user's authenticated browser session. They solve different security problems.
Written by
James Okafor
DevOps engineer covering containers, CI/CD, and infrastructure workflows.