Skip to content
Aditya Bhalsod
← Web
WebIntermediate

Tracing a JWT From a FastAPI Login to a React Fetch Call

A walk through the JWT flow in fastapi-reactjs-crud, from token issue to a FastAPI dependency to React's fetch call, plus the limits I would fix first.

  • #fastapi
  • #react
  • #jwt
  • #authentication
Contents
  1. Issuing the token
  2. Protecting routes with a dependency
  3. Attaching and dropping the token in React
  4. Where it falls short
  5. When this is good enough

fastapi-reactjs-crud is a full-stack CRUD app. The backend is FastAPI with SQLAlchemy and PostgreSQL, the frontend is React and TypeScript, and a Compose file runs all three. The domain is small (users own items), so the interesting part is how a request proves who sent it.

This post follows one JWT from the login route to a fetch call in the browser. Then it lists the places where the auth is thinner than a real product needs. I can see those gaps in the code, and you should know about them before you copy any of it.

Issuing the token

POST /api/auth/login checks the password against a bcrypt hash through passlib, then signs a token with python-jose. The claims are the user id as sub and the username.

Python
access_token_expires = timedelta(minutes=30)
access_token = create_access_token(
    data={"sub": str(user.id), "username": user.username},
    expires_delta=access_token_expires,
)

The signing itself lives in backend/auth.py. It adds an exp claim and encodes with SECRET_KEY and the configured algorithm, which defaults to HS256.

Python
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt

The login route is limited to five attempts a minute per client address with slowapi.

Protecting routes with a dependency

Three small dependencies stack on top of each other. HTTPBearer pulls the token out of the Authorization header. get_current_user decodes it and loads the user. get_current_active_user rejects users whose is_active flag is false.

Python
security = HTTPBearer()

def get_current_user(
    credentials: HTTPAuthorizationCredentials = Depends(security),
    db: Session = Depends(get_db),
) -> User:
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    token_data = verify_token(credentials.credentials, credentials_exception)
    user = get_user_by_username(db, username=token_data.username)
    if user is None:
        raise credentials_exception
    return user

verify_token decodes with an explicit algorithms=[ALGORITHM] list, which is the right habit. Every route in routers/items.py takes get_current_active_user as an argument, so adding auth to a new route is one line.

The token alone is not the authorization, though. Each items query also filters on Item.owner_id == current_user.id. Asking for another user's item id gets the same 404 as asking for one that does not exist. That filter is the part I would keep exactly as it is.

One oddity: the token carries the id as sub, but the lookup uses username. It works because usernames are unique in the model. I would look the user up by id.

Attaching and dropping the token in React

The client uses plain fetch. Every call goes through apiRequest in frontend/src/utils/api.ts, which reads the token from localStorage each time it runs.

TypeScript
const token = localStorage.getItem('access_token');
if (token) {
  defaultHeaders.Authorization = `Bearer ${token}`;
}

On startup, AuthProvider looks for a stored token, asks /api/auth/me who it belongs to, and removes it if that request fails. login writes the token after a successful response, and logout removes it. ProtectedRoute shows a spinner while loading is true, then redirects to /login when isAuthenticated is false.

That guard is a convenience for the user. The server does the enforcing. Someone who edits the JavaScript to skip it gets an empty page shell and 401 responses from every API call.

Where it falls short

  • Storage. The token sits in localStorage, so any script that runs on the page can read it. An HttpOnly cookie keeps it out of reach of JavaScript, at the cost of thinking about CSRF.
  • Expiry. Tokens last 30 minutes and there is no refresh token. The string 401 appears nowhere in frontend/src, and the token is only checked at startup. After it expires the user still looks signed in, and the failed requests show their error text on the page (ItemsList.tsx does this) until a reload sends them to the login page.
  • Logout. It only clears the token in the browser. There is no logout endpoint and no revocation list, so a copied token works until exp.
  • Secret. The placeholder your-super-secret-key-change-in-production-with-random-32-chars is the fallback in auth.py, and it is also set in docker-compose.yml and .env.example. Run Compose as shipped and your tokens are signed with a string that is public. Anyone holding it can mint a valid token for any existing username.

When this is good enough

For a starter or a demo, the shape is right. The dependencies are short, the ownership filter is in every query, and the client is easy to read. I would not put it in front of real users yet.

Before that, I would add a 401 branch in apiRequest that calls logout, move to a short-lived access token with a refresh path, and drop the default secret so the app refuses to start without one. The password reset would need real email delivery. None of that changes the structure. The gaps are all in the details around the token.

Found this useful? Share it with your team.

Keep reading

More from Web and beyond