CORS (Cross-Origin Resource Sharing) is a security mechanism enforced by browsers that blocks cross-origin requests unless the server explicitly allows them.

By default, browsers prevent cross-origin requests. For example, if your frontend (http://example.com) tries to fetch data from http://api.example.com, the request will be blocked unless the API server enables CORS.

Installation

npm install cors

Basic Usage

cors is commonly used with Express.js to enable cross-origin requests.

Enable CORS for All Requests

const express = require("express");
const cors = require("cors");

const app = express();
app.use(cors()); // Allows all origins by default

app.get("/data", (req, res) => {
  res.json({ message: "CORS is enabled!" });
});

app.listen(3000, () => console.log("Server running on port 3000"));

Restrict CORS to Specific Origins

You can allow requests only from a specific domain:

app.use(
  cors({
    origin: "<https://example.com>", // Only allow requests from this domain
  })
);

Allow Specific HTTP Methods

app.use(
  cors({
    origin: "<https://example.com>",
    methods: ["GET", "POST"], // Only allow GET and POST requests
  })
);

Allow Custom Headers

app.use(
  cors({
    origin: "<https://example.com>",
    allowedHeaders: ["Content-Type", "Authorization"],
  })
);