JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
A React app logs in to a FastAPI Helpdesk API, keeps the JWT in memory, stamps Authorization: Bearer on every call from one fetcher, guards pages with RequireAuth, and reacts to the server's 401 and 403.
What you will learn
- Log in against a FastAPI token endpoint and read what a JWT contains
- Keep the token in memory and stamp it on every request from one fetcher
- Guard routes with a RequireAuth component and return the user to the page they asked for
- Handle 401 by logging out and treat 403 as the server's lock, not the hidden button
Before you start
- A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
- Server State With TanStack Query
Think of a concert wristband. You get it once at the entrance, and you show it at every gate after that. The gates decide whether you get in; the wristband just has to be on your wrist.
A React app works the same way with a JWT. It logs in once, keeps the token, and shows it on every request. The server decides. This article follows the Helpdesk app (React) and the Helpdesk API (FastAPI), and every status and body below is from a saved run.
One token, three trips
Send the credentials, get a token
The login page sends a POST to /api/auth/token with a username and a password. For the customer Olivia, the API answered 200 with three fields:
{"accessToken": "eyJhbGciOi...", "tokenType": "Bearer", "expiresIn": 900}
(The token is shortened here.) 900 seconds is fifteen minutes. The app keeps accessToken, and that is all a login does. A wrong password gets a 401 in Problem Details format:
401 Unauthorized
WWW-Authenticate: Bearer
Content-Type: application/problem+json
{"detail":"Wrong username or password","instance":"/api/auth/token","status":401,"title":"Unauthorized"}
The server never says which of the two was wrong. The login form shows Wrong email or password:
import { useLocation, useNavigate } from 'react-router'
import { useLogin } from '../api/helpdesk'
import { setToken } from './session'
export default function Login() {
const navigate = useNavigate()
// the page the guard turned the user away from
const from = useLocation().state?.from
const back = from?.pathname ?? '/tickets'
const login = useLogin({
mutation: {
onSuccess: (res) => {
setToken(res.accessToken ?? null)
navigate(back, { replace: true })
},
},
})
function submit(form: FormData) {
login.mutate({
data: {
username: String(form.get('username')),
password: String(form.get('password')),
},
})
}
return (
<form action={submit}>
<input name="username" placeholder="Email" />
<input
name="password"
type="password"
placeholder="Password"
/>
<button disabled={login.isPending}>
Log in
</button>
{login.error?.status === 401 && (
<p className="error">
Wrong email or password
</p>
)}
</form>
)
}
A token has three parts
A JWT is one long string with two dots in it: header.payload.signature. The project's token demo decoded the captured token like this:
- Header:
{"alg":"HS256","typ":"JWT"} - Payload (the claims):
iss"helpdesk",sub(the user's email),iatandexp900 seconds apart, androles, here["CUSTOMER"]. - Signature: 43 characters. Only the server, which holds the secret, can check it.
export type User = {
email: string
roles: string[]
exp: number
}
// A JWT is header.payload.signature. The payload is
// only base64url text: the client can read it, but
// it can NOT check the signature. The server does.
export function decode(token: string): User {
const payload = token.split('.')[1]
const base64 = payload
.replace(/-/g, '+')
.replace(/_/g, '/')
const claims = JSON.parse(atob(base64))
return {
email: claims.sub,
roles: claims.roles ?? [],
exp: claims.exp,
}
}
The payload is only base64url text, so the client can read it to show who is logged in. It cannot check the signature, so it never trusts the payload for a decision. That is the server's job, in the API's auth.py (an excerpt):
def issue_token(username: str, role: str) -> str:
now = int(time())
claims = {"iss": "helpdesk", "sub": username, "iat": now, "exp": now + EXPIRES_IN, "roles": [role]}
return jwt.encode(claims, SECRET, algorithm=ALGORITHM)
bearer = HTTPBearer(auto_error=False) # we answer the 401 ourselves, as application/problem+json
def current_user(credentials: HTTPAuthorizationCredentials | None = Depends(bearer)) -> dict:
"""The claims of a valid token. No token, a bad one or an expired one is a 401."""
if credentials is None:
raise Unauthorized("A bearer token is required")
try:
return jwt.decode(credentials.credentials, SECRET, algorithms=[ALGORITHM])
except jwt.ExpiredSignatureError:
exp = jwt.decode(credentials.credentials, options={"verify_signature": False})["exp"]
when = datetime.fromtimestamp(exp, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
raise Unauthorized(f"Jwt expired at {when}", invalid_token=True)
except jwt.InvalidTokenError:
raise Unauthorized("Malformed or unsigned token", invalid_token=True)
def require_admin(claims: dict = Depends(current_user)) -> dict:
"""Signed in is not enough: this route is for the ADMIN."""
if "ADMIN" not in claims.get("roles", []):
raise Forbidden()
return claims
The token lives in memory
// The token lives in memory only. A refresh forgets
// it, but it is not in localStorage, where any
// script on the page could read it.
let token: string | null = null
const listeners = new Set<() => void>()
export const getToken = () => token
export function setToken(next: string | null) {
token = next
listeners.forEach((listen) => listen())
}
export const clearSession = () => setToken(null)
export function subscribe(listen: () => void) {
listeners.add(listen)
return () => void listeners.delete(listen)
}
// BREAK IT: in setToken, localStorage.setItem('token', next)
// survives a refresh, but every script on the page can read it
setToken puts the token in one module variable and tells the listeners. clearSession is setToken(null). Keeping it in memory is a choice with a price: a refresh forgets it and the user logs in again. The other choice, localStorage, survives a refresh, but every script on the page can read it.
import { useSyncExternalStore } from 'react'
import { decode } from './jwt'
import { getToken, subscribe } from './session'
// re-renders every user of it when the token changes
export function useSession() {
const token = useSyncExternalStore(subscribe, getToken)
return { token, user: token ? decode(token) : null }
}
useSyncExternalStore re-renders every component that uses useSession whenever the token changes.
One fetcher stamps every request
import { clearSession, getToken } from '../auth/session'
// empty in development: the dev proxy forwards /api
const base = import.meta.env.VITE_API_URL ?? ''
export class ApiError extends Error {
status: number
body: unknown
constructor(status: number, body: unknown) {
super(`HTTP ${status}`)
this.status = status
this.body = body
}
}
// the generated hooks use this as their error type
export type ErrorType<T = unknown> =
T extends unknown ? ApiError : never
export async function customFetch<T>(
url: string,
options: RequestInit,
): Promise<T> {
const headers = new Headers(options.headers)
const token = getToken()
// every request leaves through here: stamp it once
if (token) {
headers.set('Authorization', `Bearer ${token}`)
}
const init = { ...options, headers }
const res = await fetch(base + url, init)
const text = await res.text()
const body = text ? JSON.parse(text) : undefined
// expired or invalid token: forget it, the guard
// then sends the user to /login
if (res.status === 401) clearSession()
if (!res.ok) throw new ApiError(res.status, body)
return body as T
}
Every generated hook (useGetTickets, useDeleteTicket and the rest) calls this one function. If there is a token, it sets Authorization: Bearer <token>. Four hooks or forty, the header is added in one place. Line 38 is the other half: on a 401 it forgets the token.
A guard turns away anyone without a token
import {
Navigate,
Outlet,
useLocation,
} from 'react-router'
import { useSession } from './useSession'
export default function RequireAuth() {
const { token } = useSession()
const from = useLocation()
// no token: go to /login, and remember this page
if (!token) {
return (
<Navigate
to="/login"
state={{ from }}
replace
/>
)
}
return <Outlet />
}
import { Navigate, type RouteObject } from 'react-router'
import Login from './auth/Login'
import RequireAuth from './auth/RequireAuth'
import Layout from './Layout'
import TicketPage from './TicketPage'
import Tickets from './Tickets'
export const routes: RouteObject[] = [
{
element: <Layout />,
children: [
{ path: '/login', element: <Login /> },
{
// everything inside needs a token
element: <RequireAuth />,
children: [
{ path: '/tickets', element: <Tickets /> },
{ path: '/tickets/:id', element: <TicketPage /> },
],
},
{ path: '*', element: <Navigate to="/tickets" replace /> },
],
},
]
Everything inside the RequireAuth route needs a token. With none, the guard returns <Navigate to="/login" state={{ from }} replace />, and state.from remembers the page the user asked for. In the browser run, opening /tickets with no token went straight to /login.
After a good login, Login.tsx reads state.from and calls navigate(back, { replace: true }). replace means the back button does not return to the login form. The user lands on /tickets and sees the fifty tickets.
A 401 means log in again
A token made to live only two seconds (the API was started with TOKEN_SECONDS=2) and used after that got:
GET /api/tickets (Authorization: Bearer, expired token)
401 Unauthorized
WWW-Authenticate: Bearer error="invalid_token", error_description="Jwt expired at 2026-11-02T19:06:00Z"
{"detail":"Jwt expired at 2026-11-02T19:06:00Z","instance":"/api/tickets","status":401,"title":"Unauthorized"}
The fetcher sees the 401 and calls clearSession(). With no token, the guard sends the user to /login. The browser run showed the same path a different way: the API was restarted with a new secret, so the old token no longer checked out, GET /api/tickets answered 401, and the page landed on /login with Log in in the top bar.
A top bar that knows the user
import { useQueryClient } from '@tanstack/react-query'
import {
Link,
Outlet,
useNavigate,
} from 'react-router'
import { clearSession } from './auth/session'
import { useSession } from './auth/useSession'
export default function Layout() {
const { user } = useSession()
const queryClient = useQueryClient()
const navigate = useNavigate()
function logOut() {
clearSession()
queryClient.clear() // forget the old tickets
navigate('/login')
}
return (
<main>
<header>
<Link to="/tickets">Helpdesk</Link>
{user ? (
<span>
{user.email} ({user.roles.join(', ')})
<button onClick={logOut}>Log out</button>
</span>
) : (
<Link to="/login">Log in</Link>
)}
</header>
<Outlet />
</main>
)
}
With no token, the bar shows a Log in link. After Olivia logs in, it shows her email and (CUSTOMER), read from the token's payload; for Mason, the admin, it shows (ADMIN). Log out forgets the token and calls queryClient.clear(), so the next user never sees the old tickets.
Hide the button, and let the server say no
import { useQueryClient } from '@tanstack/react-query'
import { Link } from 'react-router'
import {
getGetTicketsQueryKey,
useDeleteTicket,
useGetTickets,
} from './api/helpdesk'
import { useSession } from './auth/useSession'
export default function Tickets() {
const { data, isPending } = useGetTickets()
const queryClient = useQueryClient()
const remove = useDeleteTicket({
mutation: {
onSuccess: () =>
queryClient.invalidateQueries({
queryKey: getGetTicketsQueryKey(),
}),
},
})
const del = (id: number) => remove.mutate({ id })
// hiding the button is for the user; the server
// answers 403 to anyone who is not an ADMIN anyway
const roles = useSession().user?.roles ?? []
const isAdmin = roles.includes('ADMIN')
if (isPending) return <p>Loading tickets...</p>
return (
<table>
<tbody>
{data?.map((t) => (
<tr key={t.id}>
<td>
<Link to={`/tickets/${t.id}`}>
#{t.id}
</Link>
</td>
<td>{t.subject}</td>
<td>{t.status}</td>
<td>
{isAdmin && (
<button onClick={() => del(t.id!)}>
Delete
</button>
)}
</td>
</tr>
))}
</tbody>
</table>
)
}
That is Tickets.tsx. Only an admin may delete. Olivia's page showed 0 Delete buttons; Mason's showed 50, and his delete answered 204 and the list showed 49 rows. But hiding a button only helps the user. A DELETE for ticket 5 sent anyway with Olivia's token got:
403 Forbidden
WWW-Authenticate: Bearer error="insufficient_scope"
{"detail":"The request requires higher privileges than your token has","instance":"/api/tickets/5","status":403,"title":"Forbidden"}
The hidden button is for the user. The 403 is the lock, from require_admin on the server.
Common mistakes
- Trusting the decoded payload. The client can read it, and anyone can edit their own copy. Only the server's signature check counts.
- Adding the header in each component. One fetcher, one place. Miss one call and it fails with a 401.
- Ignoring 401 in the client. Without
clearSession()the app keeps sending a dead token and the user is stuck. - Treating a hidden button as security. The server must check the role on every request.
- Keeping old data after log out. Clear the query cache, or the next user sees the last user's tickets.
Quick recap
| Step | Where | In the run |
|---|---|---|
| Log in once | Login.tsx, useLogin | 200, token, expires in 900 s |
| Keep it in memory | session.ts | a refresh forgets it |
| Stamp every request | fetcher.ts | Authorization: Bearer ... |
| Guard the pages | RequireAuth.tsx | /tickets without a token goes to /login |
| Expired or bad token | 401, clearSession() | Jwt expired at ... |
| Wrong role | server's require_admin | 403 Forbidden |
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Server State With TanStack Query: One Key, One Request, One Cache
Three components need the same list of books. Fetch it by hand and you get three requests; ask TanStack Query for one key and you get one. With real request counts, retries and a quiet refetch on tab focus.
Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
Add a book with useMutation and let invalidateQueries refetch the list, then make delete instant: snapshot, remove the row in 3 ms, roll back on a 404 and refetch the truth in onSettled.
Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
Let the API's OpenAPI spec write your React client: Orval turns /v3/api-docs into TypeScript types, useGetBooks and a Zod schema, and a renamed field becomes error TS2339 at BookList.tsx line 26.
A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
Build the React screen before the API exists: Orval writes MSW handlers and faker data from the spec, a service worker answers GET /api/books inside the browser, and npm run dev:real switches back to the real server.
