Category: 09. Cors

https://cdn3d.iconscout.com/3d/premium/thumb/picture-3d-icon-download-in-png-blend-fbx-gltf-file-formats–photography-photo-image-content-creator-pack-theatre-icons-5449075.png

  • CORS with Authentication

    When dealing with authentication (e.g., cookies or JWT), you need to ensure CORS configuration allows credentials:

    const corsOptions = {
      origin: 'http://example.com',
      methods: 'GET,POST',
      allowedHeaders: 'Content-Type,Authorization',
      credentials: true, // Allow credentials (cookies, headers)
    };
    
    app.use(cors(corsOptions));
    

    Make sure that the client-side code also includes credentials in requests:

    fetch('http://api.example.com/data', {
      method: 'GET',
      credentials: 'include' // Include cookies in the request
    });
    
  • Using cors with Non-Express Frameworks

    If you’re using other HTTP frameworks or libraries, you’ll need to manually handle CORS. Here’s a brief example using http module:

    const http = require('http');
    
    const server = http.createServer((req, res) => {
      res.setHeader('Access-Control-Allow-Origin', 'http://example.com');
      res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
      res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization');
      
      if (req.method === 'OPTIONS') {
    
    res.writeHead(204); // No content
    res.end();
    return;
    } // Your usual request handling here res.end('Hello World'); }); server.listen(3000, () => { console.log('Server listening on port 3000'); });
  • Preflight Cache Control

    You can control how long browsers cache the preflight responses using the maxAge option:

    const corsOptions = {
      origin: 'http://example.com',
      methods: 'GET,POST,PUT,DELETE,OPTIONS',
      allowedHeaders: 'Content-Type,Authorization',
      credentials: true,
      maxAge: 3600, // Cache preflight response for 1 hour
    };
    
    app.use(cors(corsOptions));
    
  • Dynamic Origin Handling

    You might want to dynamically determine whether to allow a request based on the origin. Here’s an example that allows origins based on a list or pattern:

    const allowedOrigins = ['http://example.com', 'http://another-example.com'];
    
    const corsOptions = {
      origin: (origin, callback) => {
    
    if (allowedOrigins.includes(origin) || !origin) { // Handle no origin (e.g., CURL requests)
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
    }, methods: 'GET,POST,PUT,DELETE,OPTIONS', allowedHeaders: 'Content-Type,Authorization', credentials: true, }; app.use(cors(corsOptions));
  • Using CORS in Other Frameworks

    If you are not using Express but another framework or no framework at all, you might need to handle CORS manually or use specific middleware. The general idea is similar: set appropriate headers in your HTTP responses.

  • Advanced Configuration

    For more complex scenarios, like allowing multiple origins, you can use a function for the origin option:

    const corsOptions = {
      origin: (origin, callback) => {
    
    if (['http://example.com', 'http://another-example.com'].includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
    }, methods: 'GET,POST', allowedHeaders: 'Content-Type,Authorization', }; app.use(cors(corsOptions));
  • Handling Preflight Requests

    Browsers send preflight requests (OPTIONS requests) to check if the server allows the actual request. The cors middleware handles this for you, but if you need more control, you can set up custom handling:

    app.options('*', cors(corsOptions)); // Pre-flight requests
    
  • Configuring CORS

    You can configure CORS to be more specific about which origins are allowed and other settings. For example:

    const corsOptions = {
      origin: 'http://example.com', // Allow only requests from this origin
      methods: 'GET,POST', // Allow only GET and POST methods
      allowedHeaders: 'Content-Type,Authorization', // Allow only these headers
    };
    
    app.use(cors(corsOptions));
    
  • Use cors in Your Express Application

    If you are using Express, you can set up CORS by including the cors middleware in your application. Here’s a basic example:

    const express = require('express');
    const cors = require('cors');
    
    const app = express();
    
    // Enable CORS for all origins
    app.use(cors());
    
    // Your routes here
    app.get('/', (req, res) => {
      res.send('Hello, world!');
    });
    
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => {
      console.log(Server running on port ${PORT});
    });
    
  • Install the cors package

    First, you need to install the cors package. You can do this using npm or yarn:

    npm install cors
    

    or

    yarn add cors