Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  1. Blog
  2. /
  3. React
  4. /
  5. Working with APIs

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Working with APIs

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

Log in, send the token, the server decides browser Helpdesk API 1. POST /api/auth/token 200, accessToken 2. GET /api/tickets, Authorization: Bearer ... 200, tickets 3. GET /api/tickets, no token 401 Unauthorized
Log in once, carry the token on every call, and let the server answer 200, 401 or 403.

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), iat and exp 900 seconds apart, and roles, 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

StepWhereIn the run
Log in onceLogin.tsx, useLogin200, token, expires in 900 s
Keep it in memorysession.tsa refresh forgets it
Stamp every requestfetcher.tsAuthorization: Bearer ...
Guard the pagesRequireAuth.tsx/tickets without a token goes to /login
Expired or bad token401, clearSession()Jwt expired at ...
Wrong roleserver's require_admin403 Forbidden

Keep going in React · 59 of 59

Previous
Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • One token, three trips
  • Send the credentials, get a token
  • A token has three parts
  • The token lives in memory
  • One fetcher stamps every request
  • A guard turns away anyone without a token
  • A 401 means log in again
  • A top bar that knows the user
  • Hide the button, and let the server say no
  • Common mistakes
  • Quick recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.