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:
Post a Comment