Featured image of post How to Enable CORS in Express.js: A Step-by-Step Guide

How to Enable CORS in Express.js: A Step-by-Step Guide

Learn how to easily enable CORS in Express.js to allow your API to handle cross-origin requests. This guide provides clear steps, code examples, and best practices to configure CORS for secure and accessible APIs.

Enabling CORS (Cross-Origin Resource Sharing) is essential when building APIs, as it allows your web applications to request resources from different domains.

In this guide, we’ll walk through how to enable CORS in Express.js, ensuring that your RESTful API can interact with other applications, such as those built with React.js, Vue.js, Android, and more.

What is CORS?

CORS stands for Cross-Origin Resource Sharing. It’s a mechanism that allows servers to specify who can access their resources. When you build an API using Express.js, by default, only clients from the same domain can access it. If you want your API to be accessible from different domains, you must enable CORS.

Step-by-Step Guide to Enable CORS in Express.js

1. Install the CORS Library

To enable CORS in your Express.js application, the first step is to install the cors package. This package simplifies the process of handling CORS in Node.js applications.

Run the following command to install the CORS library:

1
npm install cors --save

2. Import and Configure the CORS Middleware

After installing the package, you’ll need to import and apply the middleware in your Express application. Here’s how to do that:

1
2
3
4
5
6
7
8
const express = require('express');
const app = express();

// Import the CORS library
const cors = require('cors');

// Enable CORS
app.use(cors());

By using app.use(cors()), you’re allowing all domains to access your API. If you want to restrict access to specific domains, you can configure CORS to accept requests only from certain origins. For example:

1
2
3
app.use(cors({
  origin: 'http://example.com'
}));

This configuration restricts API access only to requests from http://example.com.

3. Enable Body Parsing with body-parser

For the API to handle incoming requests properly, you need to parse the request body. Use the body-parser middleware to parse incoming request bodies in a middleware before your handlers.

Install body-parser (if not installed) and set it up as follows:

1
2
3
4
5
6
7
8
// Import body-parser
const bodyParser = require('body-parser');

// Parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// Parse application/json
app.use(bodyParser.json());

This ensures that the data sent in requests (either JSON or URL-encoded data) is parsed and can be accessed in your routes.

4. Define and Use Routes in Express.js

Now that the necessary middleware is set up, you can define routes for your application. Below is an example of how you can import and use routes in your Express app:

1
2
3
4
5
// Import route posts
const postsRouter = require('./routes/posts');

// Use the posts route in Express
app.use('/api/posts', postsRouter);

This example shows how to organize your routes by creating a separate file for managing posts-related API routes and then using it within your main Express app.

5. Run the Express.js Server

Once everything is set up, you can start your Express server by specifying the port. Here’s how you can do it:

1
2
3
4
5
const port = process.env.PORT || 3000;

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

Your server will now be running on localhost, and CORS will be enabled, allowing other applications to make cross-origin requests to your API.

Why CORS is Important

Without CORS, modern web browsers will block requests that come from different domains for security reasons. This can prevent legitimate requests, such as from a mobile app or front-end frameworks like React or Vue, from reaching your API.

By enabling CORS in your Express.js application, you are ensuring that your API is accessible across multiple platforms and domains, which is crucial for modern web applications.

Conclusion

Enabling CORS in Express.js is a simple yet crucial step when developing APIs that interact with multiple platforms. By following the steps above, you’ll be able to set up a RESTful API that can be accessed by external clients, including web, mobile, and desktop applications.

Make sure to properly configure CORS settings, especially when dealing with sensitive data, to restrict access to trusted domains.

Related Article