Introduction to CORS & Basic Setup
Introduction
Welcome to the "Enabling & Customizing CORS in Your TypeScript REST API" course! In this first lesson, we'll explore what CORS is and set up basic CORS support in your API.
Let's start with a common scenario: You're building a web application where your frontend (running on https://myapp.com) needs to make API requests to your backend server (running on https://api.myapp.com). When you try to fetch data, the browser blocks these requests with an error like:
This happens because of the same-origin policy - a security feature built into browsers that prevents scripts from one website from accessing resources from a different domain. This is where CORS comes in.
Cross-Origin Resource Sharing (CORS) is a mechanism that allows your server to indicate which origins (domains) should be permitted to access its resources. It's not a security feature itself, but rather a controlled relaxation of the same-origin policy.
Understanding CORS Basics
CORS works through a series of HTTP headers exchanged between the browser and the server:
- The browser automatically adds an
Originheader to cross-origin requests - The server responds with specific CORS headers that tell the browser whether to allow the request
The key response headers include:
Access-Control-Allow-Origin: Specifies which origins can access the resource (e.g.,https://myapp.comor*for all origins)Access-Control-Allow-Methods: Lists permitted HTTP methods (GET, POST, etc.)Access-Control-Allow-Headers: Indicates which headers can be used in the request
Here's a visualization of how CORS works:

Simple vs. Complex Requests
CORS distinguishes between two types of cross-origin requests:
-
Simple requests that meet specific criteria (GET, POST, or HEAD methods with only standard headers)
- These follow the basic flow shown above
-
Complex requests that use other methods (PUT, DELETE) or custom headers
- For these, the browser first sends a "preflight" OPTIONS request
- The server must respond to this preflight with appropriate CORS headers
- Only if the preflight succeeds will the browser send the actual request
We'll explore preflight requests in more detail in upcoming lessons.
