Skip to content

Chapter 6.2: CORS Settings

Study Time: 30 minutes


1. CORS: What It Is and Why It's Needed

As we've learned, CORS (Cross-Origin Resource Sharing) is a browser security policy. It prevents a malicious site evil-site.com from making requests to your-bank.com on your behalf (using your cookies) and stealing data.

How it works:

  1. Frontend (browser) from domain A wants to get data from domain B.
  2. The browser sends a special "preflight" request to domain B with the OPTIONS method, asking: "Hey, domain B, can I, domain A, make a GET request to you?"
  3. Backend (server on domain B) must respond with special HTTP headers, for example: Access-Control-Allow-Origin: A.
  4. If the server's response allows the request, the browser sends the main GET request. If not, it blocks it and issues a CORS error.

💡 Space Analogy:

Before teleporting the captain to a foreign station (sending a POST request), the ship (browser) sends a drone (OPTIONS request) with the question: "Station, do you accept teleportation from the starship 'Enterprise'?". The station (API) replies: "Yes, reception from 'Enterprise' is authorized" (Access-Control-Allow-Origin header). Only then does teleportation begin.


2. Configuring CORS in Laravel (Modern Approach for Laravel 11+)

In Laravel 11+, CORS configuration has become much simpler and does not require publishing the config/cors.php file if you need basic settings. Everything is managed through the .env file and bootstrap/app.php.

Step 1: Configuration via Environment Variables

Open your .env file. Laravel provides variables by default to manage CORS for the API.

# .env

# ... other variables

# Specify the paths for which CORS will be active.
# 'api/*' is the standard value for all API routes.
CORS_PATHS=api/*

# Specify the allowed origins (domains).
# For development, specify the address of your frontend.
# You can list them separated by commas, without spaces.
CORS_ALLOWED_ORIGINS=http://localhost:5500,http://127.0.0.1:5500

# Other settings (usually can be left as default)
CORS_ALLOWED_METHODS=*
CORS_ALLOWED_HEADERS=*
CORS_EXPOSED_HEADERS=
CORS_MAX_AGE=0
CORS_SUPPORTS_CREDENTIALS=false

Key variables:

  • CORS_ALLOWED_ORIGINS: The most important variable. Here you list the domains from which requests are allowed. * allows everyone, but this is

extremely insecure for production.

  • CORS_PATHS: The paths to which these rules apply. api/* means everything that starts with /api/.

After changing .env, you do not need to restart the server if you are using php artisan serve. The changes will be picked up automatically.

Step 2 (Optional): Advanced Configuration in bootstrap/app.php

If you need more complex logic (for example, allowing subdomains with patterns), you will still have to publish the configuration file and configure the middleware. But for 95% of cases, the .env file is sufficient.

The php artisan install:api command automatically configures the basic CORS middleware for API routes in the bootstrap/app.php file. It looks like this:

// bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    // This line will already be added by the install:api command
    // It enables CORS handling for all API routes
    $middleware->api(base_path('routes/api.php'));
})

Inside ->api(), Laravel already uses the HandleCors middleware, which reads the settings from your .env. Everything is simple and out of the box.

⚠️ Important! Do not use CORS_ALLOWED_ORIGINS='*' on a production server if your API is not completely public. This opens up a potential vulnerability. Always list the specific domains of your frontend.


3. Configuring CORS in FastAPI

FastAPI uses the concept of Middleware to handle cross-cutting concerns like CORS.

Step 1: Open the main file of your application

This is the file where you create an instance of FastAPI (usually main.py).

Step 2: Add CORSMiddleware

FastAPI provides a ready-made middleware for configuring CORS.

# main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware # 1. Import the middleware

app = FastAPI(
    title="SpaceAPI",
    description="API for managing planets in the galaxy",
    version="1.0.0"
)

# 2. List of allowed origins
origins = [
    "http://localhost:5500",
    "http://127.0.0.1:5500",
    # In production, this will be the domain of your frontend
    # "https://my-awesome-app.com",
]

# 3. Add the middleware to the application
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,  # Allow the specified origins
    allow_credentials=True, # Allow cookies (will be needed for authentication)
    allow_methods=["*"],    # Allow all methods (GET, POST, etc.)
    allow_headers=["*"],    # Allow all headers
)

# ... your routers and the rest of the code here

Step 3: Restart the Uvicorn Server The Uvicorn server usually reloads automatically when the code changes. If not, restart it manually. Now your FastAPI server will correctly respond to OPTIONS requests from the frontend.


Reinforcement Quiz

1. The request that the browser sends before the main one to check CORS is called:

2. In modern Laravel (11+), basic CORS settings are mainly set in:

3. In FastAPI, to configure CORS, you use:

4. Which CORS_ALLOWED_ORIGINS value is the most secure for production?


🚀 Chapter Summary:

You have become a "diplomat of interstellar communications"! Your APIs can now securely interact with external applications using modern and correct approaches.

  • ✅ Understood the mechanism of CORS and preflight requests.
  • 🔧 Configured CORS for Laravel 11+ through the .env file.
  • ⚙️ Configured CORS for FastAPI using CORSMiddleware.
  • 🛰️ Successfully established communication between the frontend and backend.

The communication bridge is built and secured. Now you can think about how to let only "authorized personnel" cross this bridge.

📌 Check:

  • The main success criterion is the absence of CORS errors in the browser console when requesting data from the frontend.
  • In the "Network" tab of the developer tools, you can see two requests to your API: the first with the OPTIONS method (status 200/204) and the second with the GET method (status 200). This is a clear demonstration of how CORS works.