Node.js CORS – A Complete Guide with Express.js Examples

Introduction

When developing web applications, your frontend and backend may run on different origins. For example, a React application might run on http://localhost:5173, while a Node.js API runs on http://localhost:3000.

When the frontend tries to access the API, the browser may block the request because the two origins are different and the server has not allowed that cross-origin access.

This is where CORS (Cross-Origin Resource Sharing) becomes important. CORS is a browser security mechanism that allows a server to specify which origins can access its resources.

In Node.js, you can configure CORS by setting the appropriate HTTP response headers or by using the cors middleware package with Express.js.

In this tutorial, you will learn what CORS is, how it works, how to enable CORS in Node.js, and how to configure it securely for different applications.

What Is CORS in Node.js?

CORS stands for Cross-Origin Resource Sharing. It is a browser-enforced mechanism that controls whether a web page can read responses from a server hosted on a different origin.

An origin consists of three parts:

  • Protocol, such as http or https.
  • Hostname, such as example.com or localhost.
  • Port, such as 3000 or 5173.

If any of these parts differs, the origins are different.

For example:

Frontend URL Backend URL Same Origin?
http://localhost:3000 http://localhost:3000/api Yes
http://localhost:5173 http://localhost:3000/api No
http://example.com https://example.com/api No
https://app.example.com https://api.example.com No

CORS lets a server indicate which cross-origin requests a browser is allowed to make and which responses the browser is allowed to expose to frontend JavaScript.

Important: CORS is primarily a browser security mechanism. It does not replace authentication, authorization, or other API security controls, and it does not prevent non-browser clients such as command-line tools from sending requests.

Why Is CORS Used in Node.js?

CORS is useful when your frontend and backend are hosted on different origins.

Common examples include:

  • A React or Angular frontend accessing a Node.js API.
  • A Vue.js application requesting data from an Express server.
  • A separate frontend website communicating with a backend API.
  • Development environments where frontend and backend servers use different ports.

For example, suppose your frontend is hosted at:


http://localhost:5173

Your Express API runs at:


http://localhost:3000

When frontend JavaScript calls the API, the browser checks the server’s CORS response headers. If the server does not allow the frontend’s origin, the browser may prevent the frontend from reading the response.

Configuring CORS on the server allows the browser to make permitted cross-origin requests.

How Does CORS Work?

CORS generally works through HTTP request and response headers.

1. The Browser Sends a Request

For a simple cross-origin request, the browser includes an Origin header.


GET /api/users HTTP/1.1
Host: localhost:3000
Origin: http://localhost:5173

The Origin header tells the server which website initiated the request.

2. The Server Returns CORS Headers

If the server permits the origin, it can respond with a header such as:


Access-Control-Allow-Origin: http://localhost:5173

This tells the browser that the specified origin is permitted to read the response.

3. The Browser Makes the Response Available

The browser checks the relevant CORS headers. If the response satisfies the CORS rules, frontend JavaScript can access it.

If the server does not provide the required permission, the browser may block access to the response and display a CORS error in the console.

What Is the CORS Middleware in Node.js?

In Express.js applications, the cors package provides middleware for configuring CORS response headers.

It supports settings such as:

  • Allowed origins.
  • Allowed HTTP methods.
  • Allowed request headers.
  • Credentialed requests.
  • Preflight request handling.

The middleware does not automatically authenticate users or protect private endpoints. You must still implement authentication and authorization where required.

How to Enable CORS in Node.js Using Express

Let’s create a simple Express application and enable CORS using the cors package.

Step 1: Create a Node.js Project

Create a project directory:


mkdir nodejs-cors-example
cd nodejs-cors-example
npm init -y

Install Express and the CORS middleware:


npm install express cors

Step 2: Create the Express Server

Create a file named server.js:


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

const app = express();

app.use(cors());

app.get('/', (req, res) => {
    res.send('Node.js CORS Example');
});

app.get('/api/users', (req, res) => {
    res.json([
        { id: 1, name: 'John' },
        { id: 2, name: 'Sarah' }
    ]);
});

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

Step 3: Run the Server

Start the application:


node server.js

The server runs at:


http://localhost:3000

Open the following URL in your browser:


http://localhost:3000/api/users

You should see a JSON response containing two users.

In this example, app.use(cors()) enables the middleware with its default configuration. It allows cross-origin browser requests from any origin for the routes where it is applied.

This setting is convenient for learning and some public APIs, but for a private or production application, you should usually configure an explicit allowlist of trusted origins.

Configure CORS for a Specific Origin

Allowing every origin may not be appropriate for an application that is intended to be accessed only by your own frontend.

You can restrict access to a particular origin by configuring the origin option.


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

const app = express();

app.use(cors({
    origin: 'http://localhost:5173'
}));

app.get('/api/data', (req, res) => {
    res.json({
        message: 'CORS is configured for the frontend'
    });
});

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

Here, the server permits the browser origin http://localhost:5173.

If your frontend uses a different port or domain, update the configuration to match the actual origin.

An origin does not include a path. For example, http://localhost:5173/app is not a valid origin value; the origin is http://localhost:5173.

Allow Multiple Origins in Node.js

Some applications have separate frontend environments for local development, testing, and production.

You can use an allowlist to permit multiple known origins.


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

const app = express();

const allowedOrigins = [
    'http://localhost:5173',
    'http://localhost:4200',
    'https://app.example.com'
];

const corsOptions = {
    origin: function (origin, callback) {
        if (!origin || allowedOrigins.includes(origin)) {
            return callback(null, true);
        }

        return callback(new Error('Origin not allowed by CORS'));
    }
};

app.use(cors(corsOptions));

app.get('/api/data', (req, res) => {
    res.json({
        message: 'Request successful'
    });
});

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

The callback checks the incoming origin against the allowlist.

The !origin condition permits requests without an Origin header, which can include command-line tools and some non-browser clients. It does not mean those clients are trusted or authenticated. Remove this condition if your application specifically requires an Origin header, while remembering that the header itself is not a security credential.

In production, use your actual trusted frontend origins instead of the example domains.

Configure Allowed HTTP Methods

CORS can restrict which HTTP methods a browser is allowed to use for cross-origin requests.

For example, an API might permit GET, POST, and PUT.


app.use(cors({
    origin: 'http://localhost:5173',
    methods: ['GET', 'POST', 'PUT']
}));

This configuration advertises the permitted methods through CORS headers.

It is important to understand that CORS method settings are not a replacement for server-side route restrictions. Your API must still reject unsupported or unauthorized operations.

Configure Allowed Request Headers

Frontend applications sometimes need to send headers such as Content-Type or Authorization.

You can configure allowed request headers as follows:


app.use(cors({
    origin: 'http://localhost:5173',
    methods: ['GET', 'POST', 'PUT'],
    allowedHeaders: ['Content-Type', 'Authorization']
}));

This tells the browser which request headers it may use for permitted cross-origin requests.

For example, if your frontend sends a JWT in an Authorization header, that header generally needs to be allowed for the cross-origin request.

Allowing the header does not verify the JWT. Your backend must validate the token and check the user’s permissions separately.

What Is a CORS Preflight Request?

A preflight request is an OPTIONS request that a browser sends before certain cross-origin requests to check whether the actual request is permitted.

Preflight requests commonly occur when a request uses:

  • Methods such as PUT, PATCH, or DELETE.
  • Certain custom request headers.
  • A content type or other request configuration that does not qualify as a CORS-safelisted request.

For example, a browser may send:


OPTIONS /api/users HTTP/1.1
Origin: http://localhost:5173
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: authorization,content-type

The server’s response can include headers such as:


Access-Control-Allow-Origin: http://localhost:5173
Access-Control-Allow-Methods: GET,POST,PUT
Access-Control-Allow-Headers: Authorization,Content-Type

If the preflight response permits the intended request, the browser can proceed with the actual request.

When you apply the cors middleware at the application level using app.use(cors(…)), it normally handles preflight requests for your routes. If you configure CORS only on individual routes or use custom middleware, verify that the relevant OPTIONS requests are handled correctly.

Enable CORS with Credentials

Some applications use cookies to maintain login sessions. When a frontend makes a cross-origin request and needs to send cookies, both the frontend and backend must be configured appropriately.

Backend Configuration


app.use(cors({
    origin: 'http://localhost:5173',
    credentials: true
}));

Frontend Configuration Using Fetch


fetch('http://localhost:3000/api/profile', {
    method: 'GET',
    credentials: 'include'
})
    .then(response => {
        if (!response.ok) {
            throw new Error('Request failed');
        }

        return response.json();
    })
    .then(data => console.log(data))
    .catch(error => console.error(error));

The credentials: ‘include’ option allows the browser to include eligible cookies with the cross-origin request and respect credential-related browser rules.

Important: When allowing credentials, the server must return a specific permitted origin rather than Access-Control-Allow-Origin: *. You should also configure cookie attributes appropriately, and cross-site cookies generally require SameSite=None; Secure. Credentialed requests may need CSRF protection because browsers can send cookies automatically.

CORS vs Same-Origin Policy

Same-Origin Policy CORS
Restricts certain cross-origin interactions by default. Allows servers to grant cross-origin access through HTTP headers.
Is enforced by browsers. Is also enforced by browsers using server-provided permission headers.
Does not provide a general server configuration for allowing another origin to read responses. Defines headers that specify allowed origins, methods, headers, and credentials.

The same-origin policy is a browser security rule that restricts how a document or script from one origin can interact with resources from another origin.

CORS provides a controlled way for servers to allow certain cross-origin access.

CORS does not make an API private by itself. Any sensitive API must enforce authentication and authorization on the server.

Common CORS Errors in Node.js

Developers often encounter CORS errors when integrating a frontend with a Node.js API.

1. Missing Access-Control-Allow-Origin

Cause: The server response does not include an appropriate CORS header for the frontend’s origin.

Solution: Configure the cors middleware with the correct frontend origin and ensure it applies to the requested route.

2. Origin Not Allowed

Cause: The frontend’s origin does not match the server’s allowlist.

Solution: Check the full origin, including protocol, hostname, and port. For example, http://localhost:5173 and http://localhost:4200 are different origins.

3. Preflight Request Fails

Cause: The server does not handle the OPTIONS request correctly or does not allow the requested method or headers.

Solution: Configure the relevant CORS methods and headers and make sure middleware or routing does not reject the preflight request before it is handled.

4. Credentials with a Wildcard Origin

Cause: The server uses Access-Control-Allow-Origin: * while the browser request includes credentials.

Solution: Set a specific allowed origin and enable credentials: true on the server, along with credentials: ‘include’ on the frontend where needed.

5. Confusing CORS Errors with API Errors

Cause: A server may return an error response without the necessary CORS headers, causing the browser to report a CORS issue instead of exposing the response to frontend JavaScript.

Solution: Check the browser’s Network tab and server logs. Confirm whether the request reached the server, inspect the HTTP status, and verify the CORS headers on both successful and error responses.

CORS Security Best Practices

Follow these practices when configuring CORS in a production Node.js application.

1. Allow Only Trusted Origins

Use an explicit allowlist for private APIs. Avoid unrestricted origins when only known frontend applications should access the API.

2. Avoid Wildcard Origins with Credentials

Browsers do not permit credentialed CORS access when the server returns a wildcard allowed origin. Use a specific trusted origin for cookie-based authentication.

3. Do Not Treat CORS as Authentication

CORS controls what browser-based JavaScript can read. It does not stop all requests from being sent to the server, and it does not protect an API from non-browser clients.

Use authentication, authorization, input validation, and appropriate rate limiting independently of CORS.

4. Restrict Methods and Headers Where Practical

Allow only the methods and headers required by your frontend. This helps keep the CORS policy focused on the application’s actual needs.

5. Protect Cookie-Based Authentication

Use appropriate cookie attributes, HTTPS, and CSRF defenses. CORS alone is not a complete defense against cross-site request forgery.

6. Keep Development and Production Origins Separate

Configure local frontend origins for development and actual website origins for production. Avoid leaving development origins in production without a clear reason.

Conclusion

CORS in Node.js allows you to control which browser-based frontend origins can access responses from your API. With Express.js and the cors middleware, you can configure allowed origins, HTTP methods, request headers, credentials, and preflight behavior.

For a production application, use an explicit origin allowlist where appropriate, configure credentialed requests carefully, and remember that CORS does not replace authentication or authorization.

By understanding how CORS works and configuring it correctly, you can connect your frontend and Node.js backend while maintaining a clear browser access policy.

Related Node.js Tutorials