Configure Cross-Origin Resource Sharing (CORS)

If your frontend and backend are hosted on different origins you'll need to configure CORS.

⚠️

Determine If You Actually Need CORS

CORS is only required when your frontend and backend are hosted on different origins. To be considered the same origin, the scheme, domain and port of the frontend and backend must be the same. For example, if you're hosting both your frontend and backend under origin https://example.com, you don't need to configure CORS and can skip to Testing Session Management.

Cross-Origin Resource Sharing (CORS) is a security feature that controls how browsers can request resources from different domains. If your JavaScript frontend and backend servers are hosted on different origins, then you will need to configure CORS to allow your JavaScript frontend to make requests to your backend servers.


FastAPI CORS Configuration

First, configure your FastAPI server to use CORSMiddleware:

# src/main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware  # <-- ADD THIS
from routes.auth_routes import router as auth_router
from wristband.fastapi_auth import SessionMiddleware 

def create_app() -> FastAPI:
    app = FastAPI()
    
    app.add_middleware(SessionMiddleware, secret_key="<your-generated-password>")

    # IMPORTANT: Middleware order matters!! FastAPI middleware
    # will execute in reverse order of how they are listed here.
    # CORS should go below SessionMiddleware to execute first.

    # NEW --> Add CORS middleware here.
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["<replace_with_your_frontend_origin>"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"]
    )

    app.include_router(auth_router, prefix="/api/auth")

    # Your other application setup...



Frontend Configuration

When making requests from your JavaScript frontend to your backend, ensure you enable credentials to be sent in the request. If credentials aren't enabled, then the session cookie won't be sent in the request.

Axios

axios.defaults.withCredentials = true;

// ...or...

const apiClient = axios.create({
  baseURL: `http://localhost:8080/api`,
  headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
  withCredentials: true, // Enable credentials to be sent.
});

Fetch

fetch('http://localhost:8080/api/endpoint', {
  credentials: 'include'
})

Now that CORS is configured, your JavaScript frontend can send requests to your backend server across different origins.



What’s Next

Let's confirm that session handling and endpoint protection are working as expected.