Skip to main content

Command Palette

Search for a command to run...

CORS Preflight - The security guard

Published
2 min read
CORS Preflight - The security guard
B

Developer who is betting his career on React and TypeScript :)

This article is a continuation of my previous article on CORS. Please check that one if you need a basic understanding on CORS.

CORS mechanism is a step that browsers do to ensure security. It ensures security when dealing with Cross-Origin resources. There is one more step that the browsers will do to ensure security. Those are called Preflight requests.

Preflight requests are sent first before the actual request is sent to ensure that the other server is willing and able to accept the request, and to prevent potential security issues. This request is not sent all the time, it depends on certain factors. Preflight requests are sent when,

  1. The request method is anything other than GET or HEAD.

  2. If any custom headers are added to the request.

The Preflight requests are usually sent with the OPTIONS HTTP method. They carry the following headers with them.

HeaderDescription
OriginOrigin domain of the actual request
Access-Control-Request-MethodThe HTTP method of the actual request
Access-Control-Request-HeadersThe added custom headers in comma separated fashion (If any)

Note that in CORS configuration, not only the allowed origin, but the allowed methods and allowed headers can also be configured.

For this Preflight request, the server usually responds with a 204 No Content response. In the response headers, 3 headers will be specified based on the CORS configuration, they are

HeaderDescription
Access-Control-Allow-OriginThe allowed origin
Access-Control-Allow-MethodThe allowed methods
Access-Control-Allow-HeadersThe allowed headers
Access-Control-Max-AgeThe TTL to cache the Preflight request

With these headers, the browser will perform the CORS mechanism and decides whether to continue to make the actual request or to throw a CORS error. The Access-Control-Max-Age header is used to cache the response of the Preflight request in order to stop sending multiple requests. The usual value is 86400 seconds with is a day.

Diagram of a request that is preflighted

So that’s it folks, This was one of the many interview questions that I received during my interviews for a Front-end developer role so I thought of not only preparing, but to also share it with everyone. Hope it helps. Will be back with another blog soon, Until then!