Two Techies Blogs

DevBlog - A Blog Template Made For Developers

Welcome to my blog. Subscribe and get my latest blog post in your inbox.

Preflight CORS Requests: The Gatekeepers of Cross-Origin Requests

Published 5 months ago

CORS

CORS stands for Cross-Origin Resource Sharing. It is a security feature implemented by web browsers to prevent unauthorized access to resources on a different origin (domain, protocol, or port) than the one the website is hosted on.

Understanding Preflight CORS Requests

Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers to prevent unauthorized access to resources on a different origin (domain, protocol, or port) than the one the website is hosted on. When a web application makes a cross-origin request that could have side effects (such as modifying data on the server) or uses non-simple headers or methods, the browser sends a preflight request to check if the request is safe to send.

How Preflight Requests Work

When a cross-origin request triggers a preflight request, the browser sends an HTTP OPTIONS request to the server before sending the actual request. This OPTIONS request includes headers such as Origin, Access-Control-Request-Method, and Access-Control-Request-Headers.

The server responds to the preflight request with headers indicating whether the actual request is allowed. These headers include Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers.

Here is one example in node.js


functions.http('corsEnabledFunction', (req, res) => {
  // Set CORS headers for preflight requests
  // Allows GETs from any origin with the Content-Type header
  // and caches preflight response for 3600s

  res.set('Access-Control-Allow-Origin', '*');

  if (req.method === 'OPTIONS') {
    // Send response to OPTIONS requests
    res.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.set('Access-Control-Allow-Headers', 'Origin, access-control-allow-origin, Content-Type');
    res.set('Access-Control-Max-Age', '3600');
    res.status(204).send('');
  } else {
    res.send('Hello World!');
  }
});


If the preflight request is successful and the server indicates that the actual request is allowed, the browser will send the actual request. Otherwise, it will block the request and an error will be thrown:

Access to XMLHttpRequest at 'https://XXXXXXXXX' from origin 'https://XXXXXXXXX' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Conclusion

Preflight CORS requests are an important security feature implemented by web browsers to protect against unauthorized cross-origin requests. Understanding how preflight requests work can help you ensure that your web applications comply with CORS policies and avoid potential security vulnerabilities.