In the context of Cross-Origin Resource Sharing (CORS), a pre-flight request is a mechanism used by web browsers to determine if a certain cross-origin request is safe to send, based on the target server's stated policy.
Why is it needed?
Browsers restrict web pages from making requests to a different domain than the one the web page came from. This restriction is in place for security reasons, primarily to prevent cross-site request forgery. However, in the modern web, there's often a need to access resources (like APIs) that are hosted on different domains. CORS is a mechanism that allows restricted resources to be requested from another domain.
How does it work?
Before the actual request (like a POST or PUT request), the browser sends a preliminary request (using the HTTP OPTIONS method) to the target URL. This is the pre-flight request.
What does the pre-flight request ask?
T he pre-flight request inquires if the actual request (that follows the pre-flight) is safe to send. It sends headers such as:
- Origin: Specifies the domain making the request.
- Access-Control-Request-Method: Indicates which method (like POST, GET, etc.) will be used in the actual request.
- Access-Control-Request-Headers: Specifies which HTTP headers will be used when the actual request is made.
How does the server respond?
If the server is configured to support CORS and approves of the pre-flight request's headers, it responds with appropriate CORS-related headers such as:
- Access-Control-Allow-Origin: Specifies which origin sites are allowed. It can be a specific domain or a wildcard * to allow any domain.
- Access-Control-Allow-Methods: Lists the HTTP methods that are permitted.
- Access-Control-Allow-Headers: Indicates which headers can be used when making the actual request.
What happens next?
If the pre-flight request is successful (i.e., the server sends back a favorable response), the browser proceeds with the actual request. If not, the browser blocks the request and typically throws a CORS-related error in the console.
Not all requests require a pre-flight.
Simple requests, such as some GET requests, might not trigger a pre-flight check. However, requests that can cause side-effects (like POST, PUT, DELETE methods) or use custom headers often require a pre-flight check.