If you’ve ever worked with APIs in a web application, you might have come across a frustrating error in your browser console:
"Access to fetch at 'URL' from origin 'another-URL' has been blocked by CORS policy."
This happens because of CORS (Cross-Origin Resource Sharing). But don’t worry! In this guide, I’ll explain what CORS is, why it's needed, and how to fix CORS issues in Node.js with a simple example.
What is CORS?
CORS (Cross-Origin Resource Sharing) is a security feature built into web browsers. It controls which websites can access resources on your server.
By default, web browsers block requests that come from a different domain than the one hosting the API. This is called the Same-Origin Policy (SOP).
Example of Same-Origin Policy:
Imagine you have a website running on:
👉 https://mywebsite.com
And you are trying to fetch data from an API running on:
👉 https://api.anotherwebsite.com
Without CORS, the browser will block this request because the two URLs have different origins.
Why is CORS Needed?
CORS is important because it prevents malicious websites from stealing your data or making unauthorized API requests on behalf of users.
For example, imagine you are logged into a banking website (bank.com). If there was no CORS restriction, a hacker could create a fake website (hacker.com) and make a request to your bank to transfer money from your account.
CORS helps prevent such attacks by requiring explicit permission from the server before allowing cross-origin requests.
How Does CORS Work?
When your frontend makes a request to a different domain, the browser first asks the server if it allows cross-origin requests. The server responds with special CORS headers to indicate whether or not it allows access.
CORS Headers Example:
When a server allows cross-origin requests, it sends a response like this:
Access-Control-Allow-Origin: https://mywebsite.com Access-Control-Allow-Methods: GET, POST Access-Control-Allow-Headers: Content-Type
These headers tell the browser:
- Which origins can access the server (mywebsite.com)
- Which HTTP methods are allowed (GET, POST)
- Which headers can be included in requests (Content-Type)
If the request does not match these rules, the browser blocks it.
How to Enable CORS in Node.js?
Now, let’s see how to fix CORS issues in a Node.js application using Express.js.
Step 1: Install Express and CORS
First, if you haven’t already installed Express.js, install it using npm:
sh
CopyEdit
npm install express cors
Here, cors is a package that helps handle CORS easily.
Step 2: Create a Simple Server with CORS Enabled
Now, let’s create a simple Node.js server and enable CORS.
js
CopyEdit
const express = require('express'); const cors = require('cors'); const app = express(); // Enable CORS for all origins app.use(cors()); app.get('/data', (req, res) => { res.json({ message: 'CORS is working!' }); }); app.listen(5000, () => { console.log('Server running on port 5000'); });
Step 3: Test the API
Run your server:
node server.js
Now, if you visit http://localhost:5000/data in your browser, you will see:
{ "message": "CORS is working!" }
Restricting CORS to Specific Origins
Allowing all origins (app.use(cors())) is not always safe. You might want to allow only specific websites.
For example, to allow only https://mywebsite.com, use:
app.use(cors({ origin: 'https://mywebsite.com' }));
You may also like to read:
- Getting started with NODEJS Backend. Full Roadmap for Beginners
Allowing Specific HTTP Methods
Sometimes, you might want to allow only certain HTTP methods like GET and POST:
app.use(cors({ origin: 'https://mywebsite.com', methods: ['GET', 'POST'] }));
Allowing Custom Headers
If your API requires custom headers (like authentication tokens), you must allow them:
app.use(cors({ origin: 'https://mywebsite.com', methods: ['GET', 'POST'], allowedHeaders: ['Content-Type', 'Authorization'] }));
Handling CORS Without the cors Package
If you don’t want to use the cors package, you can manually set CORS headers:
app.use((req, res, next) => { res.setHeader('Access-Control-Allow-Origin', 'https://mywebsite.com'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); next(); });
CORS and Preflight Requests
Some requests, like POST with custom headers, trigger a preflight request. The browser first sends an OPTIONS request to check if the server allows the actual request.
To handle this in Express:
app.options('*', cors());
Or manually:
app.use((req, res, next) => { if (req.method === 'OPTIONS') { res.setHeader('Access-Control-Allow-Methods', 'GET, POST'); return res.status(200).json({}); } next(); });
Common CORS Errors and Fixes
- CORS error even with cors() enabled?
👉 Try specifying the correct origin instead of using *.
- Blocked by CORS policy when sending credentials?
👉 Enable credentials in both frontend and backend:
app.use(cors({ origin: 'https://mywebsite.com', credentials: true }));
Conclusion
CORS is an important security feature that controls who can access your API. By default, browsers block cross-origin requests for security reasons.
In this guide, we:
- Learned what CORS is and why it’s needed
- Saw how to enable CORS in Node.js using Express
- Explored different ways to configure CORS
- Learned about preflight requests and common CORS errors
With the right CORS settings, you can secure your API while allowing the right users to access it.
I hope this guide helped you understand CORS in Node.js! If you have any questions, let me know in the comments.
What is CORS in Node.js? A Simple Guide with Example