Skip to content
intermediatePhase ·

Preflight Requests

Understand OPTIONS requests and CORS preflight mechanism.

30m
0 problems
Topic Progress0%

What are Preflight Requests?

A preflight request is an OPTIONS request the browser sends before the actual request to check if the cross-origin request is allowed.

When Preflight is Triggered

Simple Requests (NO preflight):
- Method: GET, HEAD, POST
- Headers: Only Accept, Content-Language, Content-Type
- Content-Type: application/x-www-form-urlencoded,
                multipart/form-data, text/plain

Non-Simple Requests (PREFLIGHT):
- Method: PUT, PATCH, DELETE, CONNECT, TRACE
- Headers: Authorization, X-Custom-Header
- Content-Type: application/json

Preflight Flow

Browser                            Server
  |                                  |
  | 1. Actual request would be:      |
  |    PUT /api/users/123            |
  |    Content-Type: application/json|
  |    Authorization: Bearer ...     |
  |                                  |
  | 2. Browser sends preflight:      |
  |    OPTIONS /api/users/123        |
  |    Origin: https://app.example.com|
  |    Access-Control-Request-Method: |
  |      PUT                         |
  |    Access-Control-Request-Headers:|
  |      Content-Type, Authorization |
  |--------------------------------->|
  |                                  |
  | 3. Server responds:              |
  |    204 No Content                |
  |    Access-Control-Allow-Origin:  |
  |      https://app.example.com     |
  |    Access-Control-Allow-Methods: |
  |      GET, POST, PUT, DELETE      |
  |    Access-Control-Allow-Headers: |
  |      Content-Type, Authorization |
  |    Access-Control-Max-Age: 86400 |
  |<---------------------------------|
  |                                  |
  | 4. If allowed, browser sends:    |
  |    PUT /api/users/123            |
  |    Content-Type: application/json|
  |    Authorization: Bearer ...     |
  |--------------------------------->|
  |                                  |
  | 5. Server responds:              |
  |    200 OK + JSON                 |
  |<---------------------------------|

Optimizing Preflight

Access-Control-Max-Age: 86400

This caches preflight results for 24 hours, avoiding repeated OPTIONS requests.

Backend Handling

// Express.js - preflight is handled by cors middleware
app.use(cors({ origin: 'https://app.example.com' }));

// Manual handling
app.options('/api/*', (req, res) => {
  res.setHeader('Access-Control-Allow-Origin', 'https://app.example.com');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  res.setHeader('Access-Control-Max-Age', '86400');
  res.sendStatus(204);
});

Best Practices

Key Principles

  1. Follow SOLID principles
  2. Write clean, readable code
  3. Test thoroughly
  4. Document decisions
  5. Monitor in production

Implementation

  • Start simple, refactor as needed
  • Use established patterns
  • Consider trade-offs
  • Review with peers

Continuous Improvement

  • Learn from incidents
  • Update documentation
  • Share knowledge
  • Mentor others

Key Points

  • Understanding Preflight Requests is essential for production systems
  • Always consider scalability and maintainability
  • Test thoroughly before deploying to production
  • Monitor performance and set up alerting

Common Patterns

  1. Validation: Always validate input at the boundary
  2. Error Handling: Use structured error responses
  3. Logging: Log key events for debugging
  4. Testing: Unit, integration, and load tests
  5. Documentation: Keep docs updated with code changes

Practice Problems

0/3solved
Implement Preflight Requests

Design and implement a solution for Preflight Requests in a backend system. Consider scalability, error handling, and production readiness.

Solution
// Preflight Requests implementation
// Key aspects: validation, error handling, logging, testing

public class PreflightRequests {
    // Production-ready implementation
}
Preflight Requests Edge Cases

Identify and handle edge cases for Preflight Requests. What happens under high load, with invalid input, or during failures?

Solution
// Edge case handling:
// 1. Null/empty input -> validation
// 2. High load -> rate limiting, queuing
// 3. Failures -> retries, circuit breaker
// 4. Concurrent access -> locks, idempotency
Preflight Requests Testing Strategy

Write a testing strategy for Preflight Requests. Include unit tests, integration tests, and performance tests.

Solution
// Test plan:
// - Unit: 80% coverage target
// - Integration: API contracts
// - Performance: latency, throughput
// - Chaos: failure injection

Quiz

1. Which request does the browser send as a preflight?

Question 1 options

2. What header caches preflight results?

Question 2 options

3. What is the primary purpose of Preflight Requests?

Question 3 options

4. What is a common mistake when implementing Preflight Requests?

Question 4 options

Flashcards

Question

What is a preflight request?

Answer

An OPTIONS request sent by the browser before non-simple cross-origin requests

Question

How to reduce preflight requests?

Answer

Set Access-Control-Max-Age to cache preflight results

Question

What is Preflight Requests?

Answer

Preflight Requests is a key concept in backend development.

Question

When to use Preflight Requests?

Answer

Use Preflight Requests when building production systems that require reliability, scalability, and maintainability.

Question

Preflight Requests best practices

Answer

Follow SOLID principles, write clean code, test thoroughly, document decisions, and monitor in production.

Revision Notes

Key Takeaways

  • 1.Preflight = OPTIONS request before non-simple cross-origin requests
  • 2.Simple requests (GET, HEAD, POST with simple headers) skip preflight
  • 3.Access-Control-Max-Age caches preflight results
  • 4.Backend must handle OPTIONS requests

Interview Tips

  • Know what triggers a preflight
  • Understand how to optimize preflight handling

Cheat Sheet

Preflight

  • What: OPTIONS request before non-simple cross-origin
  • Triggers: PUT, PATCH, DELETE, custom headers, JSON Content-Type
  • Cache: Access-Control-Max-Age: 86400
  • Response: 204 No Content with CORS headers