Express JS CORS


CORS (Cross-Origin Resource Sharing) is a security feature implemented in web browsers that restricts how resources on a web server can be requested from another domain. By default, web browsers enforce the same-origin policy, which means that web pages can only make requests to the same domain that served the web page. CORS provides a way for servers to relax these restrictions and allow resources to be accessed from different origins.

Understanding CORS

  1. Same-Origin Policy:

    • The same-origin policy is a security measure that prevents a web page from making requests to a different domain than the one that served the web page. This policy helps prevent malicious websites from accessing sensitive data from other websites.
  2. CORS:

    • CORS is a protocol that allows servers to specify which origins are permitted to access their resources. It uses HTTP headers to determine whether a request should be allowed or blocked based on the origin of the request.

How CORS Works

  1. Preflight Requests:

    • For some types of requests (such as those with custom headers or methods other than GET and POST), the browser sends an HTTP OPTIONS request (preflight request) to the server to check if the actual request is allowed.
  2. Response Headers:

    • The server responds with CORS-specific headers that indicate whether the request from the origin is permitted. Common CORS headers include:
      • Access-Control-Allow-Origin: Specifies the allowed origins.
      • Access-Control-Allow-Methods: Specifies the allowed HTTP methods (e.g., GET, POST, PUT).
      • Access-Control-Allow-Headers: Specifies the allowed headers.
      • Access-Control-Allow-Credentials: Indicates whether credentials (such as cookies) can be included in the request.

Setting Up CORS in Express.js

To enable CORS in an Express.js application, you can use the cors middleware package. Here’s how to set it up:

  1. Install the CORS Middleware:

    Install the cors package via npm:

    npm install cors
  2. Configure and Use CORS Middleware:

    Basic Usage:

    const express = require('express'); const cors = require('cors'); const app = express(); // Use CORS middleware app.use(cors()); app.get('/', (req, res) => { res.send('Hello, world!'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });

    Custom Configuration:

    You can configure CORS to allow specific origins, methods, and headers:

    const express = require('express'); const cors = require('cors'); const app = express(); // CORS configuration options const corsOptions = { origin: 'http://example.com', // Allow requests only from this origin methods: 'GET,POST,PUT,DELETE', // Allowed HTTP methods allowedHeaders: 'Content-Type,Authorization', // Allowed headers credentials: true // Allow credentials such as cookies }; // Use CORS middleware with options app.use(cors(corsOptions)); app.get('/', (req, res) => { res.send('Hello, world!'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });

Common CORS Headers

  1. Access-Control-Allow-Origin:

    • Specifies the allowed origin(s). For example, Access-Control-Allow-Origin: * allows all origins, while Access-Control-Allow-Origin: http://example.com allows only the specified origin.
  2. Access-Control-Allow-Methods:

    • Specifies the allowed HTTP methods (e.g., GET, POST, PUT, DELETE).
  3. Access-Control-Allow-Headers:

    • Specifies which headers can be included in the request (e.g., Content-Type, Authorization).
  4. Access-Control-Allow-Credentials:

    • Indicates whether credentials (such as cookies) can be included in the request.
  5. Access-Control-Expose-Headers:

    • Specifies which response headers can be exposed to the client.
  6. Access-Control-Max-Age:

    • Specifies how long the results of a preflight request can be cached.

Handling Preflight Requests

For some requests, especially those with custom headers or methods other than GET and POST, browsers send a preflight request (OPTIONS) to check if the actual request is allowed. You don’t need to handle OPTIONS requests manually if you use the cors middleware, as it handles them automatically.

Summary

  • CORS is a protocol that allows servers to specify which origins are permitted to access their resources.
  • CORS Middleware in Express.js is implemented using the cors package, which simplifies configuring CORS.
  • CORS Headers control which origins, methods, and headers are allowed.
  • Preflight Requests are used to check permissions before sending the actual request, and the cors middleware handles these automatically.

By configuring CORS properly, you can ensure that your server interacts securely with web applications from different origins while controlling access to your resources.