How to make HTTP-only cookies secure in a React and FastAPI

1. Backend (FastAPI): Setting Secure HTTP-Only Cookies – Python

Use the Set-Cookie header with the right attributes for your cookies in FastAPI. Here’s an example:

from fastapi import FastAPI, Response, Depends
from fastapi.responses import JSONResponse
from datetime import timedelta
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# Enable CORS for your frontend origin
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://your-frontend-domain.com"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.post("/login")
def login(response: Response):
    # Set an HTTP-only, secure cookie
    token = "example_token"  # Replace with your actual token generation logic
    response.set_cookie(
        key="auth_token",
        value=token,
        httponly=True,        # Prevent JavaScript access
        secure=True,          # Use HTTPS
        samesite="Strict",    # Prevent cross-site usage
        max_age=3600,         # Set expiration in seconds
    )
    return JSONResponse(content={"message": "Logged in successfully"})

@app.post("/logout")
def logout(response: Response):
    # Remove the cookie by setting its expiration to the past
    response.delete_cookie("auth_token")
    return JSONResponse(content={"message": "Logged out successfully"})

2. Frontend (React): Working with Secure Cookies

React doesn’t need to interact directly with HTTP-only cookies as they are not accessible via JavaScript. However, you should configure fetch or axios to include cookies in requests.

Using fetch: – JavaScript

fetch("https://your-backend-domain.com/protected-route", {
  method: "GET",
  credentials: "include", // Include cookies in the request
})
  .then((response) => {
    if (response.ok) {
      return response.json();
    }
    throw new Error("Failed to fetch data");
  })
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

Using axios : – JavaScript

import axios from “axios”;

axios.defaults.withCredentials = true;

axios
.get(“https://your-backend-domain.com/protected-route”)
.then((response) => console.log(response.data))
.catch((error) => console.error(error));

Leave a Reply

Your email address will not be published. Required fields are marked *