DEV Community

Marouane Souda
Marouane Souda

Posted on

How to Avoid Triggering Preflight Requests

If you’ve ever tried to connect your frontend app to a backend API and saw a mysterious OPTIONS request fire off before your real request, you’ve encountered a preflight request.

These are a part of the Cross-Origin Resource Sharing mechanism enforced by browsers to maintain web security. They are HTTP OPTIONS requests sent by the browser before certain requests (I’ll get to which ones in a second) to check with the server if it's ok to send them.

Most of cross-origin requests will go just fine and won't require a preflight request beforehand. But for some, the browser insists on sending a preflight to ensure the actual request is safe and won’t cause issues. So...

When Do Preflight Requests Happen?

Before I answer that, let's cover one key concept: simple requests vs complex requests.

The browser classifies HTTP cross-origin requests into these two categories. If a request is simple, the browser skips the preflight. That’s the heart of this entire post.

So, if you want to avoid preflight requests, just make sure your request looks “simple” to the browser. That it:

  1. It uses one of these HTTP methods: GET, HEAD, or POST.

  2. It only includes "safe" headers, such as: Accept, Accept-Language, Content-Language, or Content-Type.

  3. Content-Type header value must be either text/plain, multipart/form-data, or application/x-www-form-urlencoded.

So, if you send a PUT, PATCH, or DELETE request, that’s complex and will trigger a preflight. Same goes for custom headers like Authorization, X-Custom-Header, or even Accept-Encoding. Also, using Content-Type: application/json? Yep, that’ll trigger one too.

The Main Topic: How to Avoid Sending Preflight Requests

I mean, other than sticking to same-origin requests (which avoid CORS entirely), just stick to simple request, really. Avoid custom headers, and stick to the usual text/plain, multipart/form-data, or application/x-www-form-urlencoded values of Content-Type header.

Other than at, if you can’t avoid a preflight (and sometimes you just can’t), you can reduce how often it happens. On your server, set the Access-Control-Max-Age header. This tells the browser to cache the preflight response for a set period of time so it won’t have to send it again for every single request.

If you find this post helpful, don't forget to drop a like or a comment, and share it. It helps me tremendously.

Top comments (2)

Collapse
 
andriy_ovcharov_312ead391 profile image
Andriy Ovcharov

Interesting. Thanks for sharing!

Collapse
 
marsou001 profile image
Marouane Souda

You're welcome!