Frontend Configuration
Fetch API
api.js
// Send request with cookies included
fetch('https://api.example.com/login', {
method: 'POST',
credentials: 'include', // Important!
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, password }),
});Axios
api.js
import axios from 'axios';
// Global configuration
axios.defaults.withCredentials = true;
// Or per request
axios.post('https://api.example.com/login', data, {
withCredentials: true // Important!
});Backend Configuration
Python FastAPI
main.py
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://your-frontend.com"], # Cannot use *!
allow_credentials=True, # Important!
allow_methods=["*"],
allow_headers=["*"],
)
@app.post("/login")
async def login(response: Response):
# Set cookie
response.set_cookie(
key="session",
value="token-value",
httponly=True,
secure=True, # HTTPS required
samesite="none", # Allow cross-site
max_age=3600 * 24 * 7 # 7 days
)
return {"message": "Login successful"}Node.js Express
server.js
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({
origin: 'https://your-frontend.com',
credentials: true // Important!
}));
app.post('/login', (req, res) => {
res.cookie('session', 'token-value', {
httpOnly: true,
secure: true,
sameSite: 'none',
maxAge: 7 * 24 * 60 * 60 * 1000 // 7 days
});
res.json({ message: 'Login successful' });
});HTTPS Required!
SameSite=None must be used with Secure=True.
This means it only works in HTTPS environments.
During development, localhost is exceptionally allowed.
Never do this!
- Use
allow_origins=["*"]together withallow_credentials=True - Store sensitive tokens in localStorage
- Set session cookies without httpOnly
Debugging Methods
- Open browser DevTools (F12) → Application → Cookies to check
- In the Network tab, verify that the Cookie header is included in request headers
- Check if Set-Cookie is present in response headers
- Verify there are no CORS-related errors in the Console