Have you ever built a cool frontend that connects to a Node.js backend, only to be greeted with this dreaded error?
Access to fetch at 'http://your-api.com' from origin 'http://your-frontend.com' has been blocked by CORS policy
Feels like trying to enter a VIP club without an invitation. 🚫😩
Well, don’t worry! The CORS (Cross-Origin Resource Sharing) middleware is here to open the door for your frontend and backend to talk to each other like best friends! 🥳
Let’s explore how to use CORS in Node.js with both CommonJS (CJS) and ES Module (ESM), along with all its options! 🚀
🌍 1. What is CORS in Node.js?
CORS (Cross-Origin Resource Sharing) is a security feature built into web browsers that prevents websites from making requests to different domains unless they are explicitly allowed.
Why is CORS important?
✅ Allows frontend and backend to communicate (especially if they are on different domains).
✅ Prevents unauthorized cross-origin requests for better security.
✅ Enables APIs to be accessed by multiple clients (e.g., web, mobile apps).
🔧 2. Install cors
Package
Before we start, we need to install the cors
middleware in our Node.js project:
npm install cors
This will work for both CJS and ESM, so let's move on to the implementation! 🚀
🔥 3. Using CORS in Node.js (CommonJS - CJS)
If your project uses CommonJS (require
), follow these steps:
📌 Basic CORS Setup in Node.js (CJS)
Open or create a server.js
file and add this code:
const express = require("express");
const cors = require("cors");
const app = express();
// Enable CORS for all requests
app.use(cors());
app.get("/", (req, res) => {
res.send("CORS is enabled! 🌍");
});
app.listen(3000, () => {
console.log("Server running at http://localhost:3000 🚀");
});
🔹 How does this work?
- The
cors()
middleware is applied to all routes. - Any frontend can now access your API without getting blocked.
🚀 4. Using CORS in Node.js (ES Module - ESM)
If you’re using ES Module (import
), don’t forget to add "type": "module"
in package.json
:
{
"type": "module"
}
📌 CORS Setup in Node.js (ESM)
Create a server.mjs
file and add this code:
import express from "express";
import cors from "cors";
const app = express();
// Enable CORS for all requests
app.use(cors());
app.get("/", (req, res) => {
res.send("CORS is enabled! 🌍");
});
app.listen(3000, () => {
console.log("Server running at http://localhost:3000 🚀");
});
🔹 Differences from CJS?
- Uses
import
instead ofrequire
. - Requires ESM activation in
package.json
.
⚙️ 5. Configuring CORS for Better Security
By default, cors()
allows all origins (*
), but in production, it’s better to restrict access to specific origins.
✅ Allow CORS for a Specific Origin
If you only want to allow a specific frontend (e.g., http://myfrontend.com
), use:
app.use(cors({
origin: "http://myfrontend.com"
}));
Now, only http://myfrontend.com
can access your API. Any other domain? Access denied! 🚫
🛠 6. Advanced CORS Options in Node.js
The cors
middleware has several options you can use to control access:
Option | Description |
---|---|
origin |
Defines which domains can access the API (* for all, or specific domains). |
methods |
Specifies which HTTP methods are allowed (e.g., GET, POST, PUT, DELETE ). |
allowedHeaders |
Defines which headers can be sent in the request. |
credentials |
Allows cookies and authentication headers (true to enable). |
maxAge |
Sets how long the CORS response is cached (in seconds). |
preflightContinue |
Passes preflight response to the next handler. |
🔥 7. Example: Restricting CORS with More Security
Let’s create a stricter CORS policy:
app.use(cors({
origin: ["http://myfrontend.com", "https://myapp.com"], // Allow specific domains
methods: ["GET", "POST"], // Allow only GET and POST
allowedHeaders: ["Content-Type", "Authorization"], // Restrict allowed headers
credentials: true, // Allow cookies
maxAge: 600 // Cache the CORS response for 10 minutes
}));
What does this do?
✅ Only allows requests from http://myfrontend.com
and https://myapp.com
.
✅ Only GET
and POST
methods are allowed.
✅ Only Content-Type
and Authorization
headers can be sent.
✅ Allows cookies for authentication.
✅ Caches CORS settings for 10 minutes (600 seconds).
⚡ 8. Handling Preflight Requests
Some requests (like PUT
, DELETE
, or requests with custom headers) trigger a preflight request (OPTIONS
method).
If you need to handle preflight manually, use:
app.options("*", cors()); // Handle preflight for all routes
This tells the browser:
🚦 "Hey, the backend allows this request. You’re good to go!"
🏆 Conclusion: No More CORS Headaches! 🎉
🎯 CORS allows your frontend and backend to communicate safely.
🎯 Works with both CommonJS (CJS) and ES Module (ESM).
🎯 By default, it allows all origins, but it’s better to restrict it in production.
🎯 You can customize allowed origins, methods, headers, and credentials for security.
🎯 Preflight requests must be handled for certain HTTP methods.
Now your frontend and backend can talk freely without any “Blocked by CORS Policy” errors! 🚀
#HappyCoding! 🎉🔥
0 Comments