Back
Web Fundamentals

CORS Explained: Cross-Origin Resource Sharing

Web Fundamentals
Build & Deployment: Monorepo, CI/CD, Strategies & Release SafetyState Management: Choosing the Right SolutionRedux: Predictable State Container (RTK + RTK Query)React Query (TanStack Query): Server State CachingData Fetching Patterns: REST, GraphQL, tRPC & Real-timeGraphQL Fundamentals for Frontend: Shape, Caching, and TradeoffsgRPC-Web Fundamentals: Browser Constraints and Proxy ModelCaching Strategies: Client, Server & EdgeData Normalization: Organizing State for PerformanceAPI Design Best Practices: Pagination, Errors, Versioning & Type SafetyAPI Versioning Strategies for Frontend CompatibilityPagination: Offset vs Cursor-BasedRate Limiting & API Resilience: Retries, Backoff, Jitter, IdempotencyHow Frontend Developers Can Handle Millions of API Requests Without Crashing EverythingBrowser Storage: Cookies, SessionStorage, LocalStorage, IndexedDBReal-time Communication: WebSockets, SSE & PollingWebRTC: Real-Time Communication in the BrowserCore Web Vitals: LCP, INP & CLSPerformance Optimization Trade-offsCritical Resource Prioritization: Optimize Loading OrderCode Splitting: Optimize Bundle Size with Dynamic ImportsTree Shaking: Eliminate Dead Code from Your BundleLazy Loading: Load Resources On-DemandResource Hints: Preload, Prefetch & PreconnectText Compression: Gzip and BrotliImage & Video Optimization: Modern Formats & TechniquesAdaptive Loading: Optimize for Device & NetworkList Virtualization: Render Large Lists EfficientlyWeb Workers vs Main Thread: Offloading Heavy WorkMemory Leaks in Frontend Apps: Detection & PreventionManaging Third-Party Scripts: Optimization StrategiesHow CDNs Work: Edge Delivery, Caching & PerformanceHTTP Caching Deep Dive: Cache-Control, ETag & RevalidationService Workers & Offline Strategy: Cache First, Network First & Update LifecyclePWA Fundamentals: Manifest, Installability & Offline UXCritical Rendering PathScript Loading: async vs deferEvent Loop: Understanding JavaScript Execution ModelJavaScript Module Systems: CJS vs ESM vs UMDDynamic Module Loading: import() FunctionImport on Interaction: Load When User InteractsImport on Visibility: Lazy Loading with IntersectionObserverBrowser Rendering Pipeline & Layout ThrashingRendering Strategies: CSR vs SSR vs SSG vs ISRStreaming SSR: Progressive HTML StreamingIslands Architecture: Independent Component HydrationReact Server Components: Zero-JS Server RenderingFramework Reactivity: React, Vue, Svelte & SolidHTTP/1.1 vs HTTP/2 vs HTTP/3 (QUIC) for Frontend PerformanceDNS Resolution: Path, TTL, Caching & Frontend ImpactCross-Site Scripting (XSS) AttacksCross-Site Request Forgery (CSRF) AttacksCORS Explained: Cross-Origin Resource SharingCORS Preflight in Practice: Credentials, Simple Requests & MisconfigurationsContent Security Policy (CSP)Why is HTTPS Secure? Understanding TLS/SSLAuthorization Best PracticesCookie Security & Session Hardening: SameSite, HttpOnly, Secure
mediumSecurity

CORS Explained: Cross-Origin Resource Sharing

TL;DRCORS is a browser security feature that controls cross-origin requests. Configure Access-Control-Allow-Origin and handle preflight OPTIONS requests.
High Signal
Google
Meta
Netflix
Agoda
Atlassian
30-Second Answerstart every interview with this

Cross-Origin Resource Sharing (CORS) is a browser security mechanism that restricts cross-origin HTTP requests. It prevents malicious sites from reading sensitive data from other origins. Proper configuration on the server side (headers) is required for legitimate cross-origin communication.

The browser is the club owner. When a request comes from a different origin (another club), the bouncer (CORS policy) checks the guest list (headers). If the origin is not allowed, the request is blocked before it reaches the server.

Cross-origin request from frontend
Browser checks CORS headers from server
Allowed → Request proceeds
Blocked → CORS error in console

1Simple vs Preflight Requests

Simple requests (GET, HEAD, POST with basic headers) are sent directly. Non-simple requests (PUT, DELETE, custom headers) trigger a preflight OPTIONS request first.

Simple Request

Browser sends actual request → Server responds with CORS headers

Preflight

Browser sends OPTIONS → Server responds with Allow headers → Browser sends actual request

2Essential CORS Headers

Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Access-Control-Allow-Credentials, and Access-Control-Max-Age.

3Server-Side Implementation

Configure CORS middleware or manually set headers. Always specify exact origins in production instead of using wildcard (*).

PropertySimple RequestPreflight Request
MethodsGET, HEAD, POST (basic Content-Type)PUT, DELETE, custom headers
PreflightNoYes (OPTIONS)
Common UseBasic data fetchingState-changing operations

Simple Request

Methods

GET, HEAD, POST (basic Content-Type)

Preflight

No

Common Use

Basic data fetching

Preflight Request

Methods

PUT, DELETE, custom headers

Preflight

Yes (OPTIONS)

Common Use

State-changing operations

Common questions

  • ›“What is CORS and why does it exist?”
  • ›“Explain the difference between simple and preflight requests.”
  • ›“How do you fix a CORS error in a full-stack app?”
  • ›“What is Access-Control-Allow-Credentials and when do you need it?”

What interviewers look for

  • Understanding of browser security model
  • Knowledge of preflight mechanism
  • Practical server configuration (headers/middleware)
  • Security awareness (never use * with credentials)

Short answer (60 sec)

CORS is a browser security feature that blocks cross-origin requests unless the server explicitly allows them via headers. Use Access-Control-Allow-Origin and handle OPTIONS preflight requests for non-simple methods.

Detailed answer (senior level)

CORS prevents malicious sites from reading data from other origins. Simple requests go directly; complex ones trigger a preflight OPTIONS request. Server must respond with proper Access-Control-* headers. In production, specify exact origins instead of wildcard. Use credentials: 'include' with Access-Control-Allow-Credentials: true and specific origin (not *).

  • Using Access-Control-Allow-Origin: * with credentials
  • Forgetting to handle OPTIONS preflight requests
  • Only configuring CORS on some endpoints
  • Not setting proper Access-Control-Allow-Headers
  • Assuming CORS is only a frontend issue
Key Takeaways
  • ✓CORS is a browser-enforced security policy
  • ✓Simple requests don't need preflight; others do
  • ✓Always specify exact origins in production
  • ✓Handle OPTIONS requests for preflight
  • ✓Use middleware like cors() in Express
  • ✓Credentials require specific origin + Allow-Credentials header
  • ✓Test cross-origin requests thoroughly
Previous TopicCross-Site Request Forgery (CSRF) AttacksNext Topic CORS Preflight in Practice: Credentials, Simple Requests & Misconfigurations

On this page