cors in express

CORS in Express

If you're building a web application with client-server architecture, you may need to make requests from your client-side code to your server-side code. However, when you try to make cross-origin requests (requests from a different domain or port), you may encounter the Cross-Origin Resource Sharing (CORS) policy.

The CORS policy is a mechanism that allows many resources (e.g., fonts, JavaScript, etc.) on a web page to be requested from another domain outside the domain the resource originated from. However, this policy is enforced by web browsers and may prevent cross-origin requests to your server-side code.

Enabling CORS in Express

To enable CORS in an Express application, you can use the cors package. You can install it via NPM:


npm install cors

After installing the package, you can use it as middleware in your Express application:


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

const app = express();

app.use(cors());

// your routes here

This middleware will enable CORS for all routes in your Express application. By default, it allows all origins, all methods, and all headers. However, you can configure it to allow only specific origins, methods, or headers:


app.use(cors({
  origin: 'https://example.com',
  methods: ['GET', 'POST'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));

In the example above, the middleware will allow cross-origin requests only from https://example.com, using the GET and POST methods, and with the headers Content-Type and Authorization.

Handling CORS Errors

If a cross-origin request is not allowed by the CORS policy, the web browser will block the request and show an error message in the console. To handle this error in your Express application, you can use the cors middleware with error handling:


const corsOptions = {
  origin: 'https://example.com',
  methods: ['GET', 'POST'],
  allowedHeaders: ['Content-Type', 'Authorization']
};

app.use(cors(corsOptions));

app.use((err, req, res, next) => {
  if (err.name === 'UnauthorizedError') {
    res.status(401).json({ error: 'Invalid authorization token' });
  } else {
    next();
  }
});

In the example above, the middleware will first check if the request is allowed by the CORS policy. If not, it will pass an error to the next middleware. The error middleware will then check if the error is an UnauthorizedError (e.g., if the request has an invalid authorization token). If so, it will send a 401 response with an error message; otherwise, it will pass the error to the next middleware.

Conclusion

CORS is an essential aspect of modern web development that allows us to build web applications with client-server architecture. However, it can be challenging to configure correctly in some cases. By using the cors package and following the best practices, you can enable CORS in your Express application and handle errors gracefully.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe