Implement JWT Authentication in React & FastAPI: A 2026 Guide
Master JWT authentication in React with FastAPI. Learn to secure routes and manage user state effectively in 2026.
Implement JWT Authentication in React & FastAPI: A 2026 Guide
Authentication is a crucial aspect of modern web applications. JSON Web Tokens (JWT) have become a popular choice for implementing authentication due to their stateless nature and ease of use. In this guide, we'll explore how to implement JWT authentication in a React frontend interacting with a FastAPI backend.
Key Takeaways
- Understand JWT and its benefits for stateless authentication.
- Implement JWT issuance and verification in FastAPI.
- Manage authentication state in React using context and hooks.
- Handle token storage and secure API requests in React.
By the end of this tutorial, you'll be equipped to handle JWT authentication in your applications, ensuring that user sessions are managed securely and efficiently. This knowledge is essential for building scalable and secure web applications.
Prerequisites
- Basic understanding of Python and JavaScript.
- Familiarity with React and FastAPI.
- Setup of Node.js and Python environments.
Step 1: Set Up FastAPI for JWT Token Issuance
First, ensure that your FastAPI application is set up to issue JWT tokens upon successful user login.
# fastapi_app/auth.py
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from datetime import datetime, timedelta
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
app = FastAPI()
@app.post("/token")
def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
user = authenticate_user(form_data.username, form_data.password)
if not user:
raise HTTPException(status_code=400, detail="Invalid credentials")
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(data={"sub": user.username}, expires_delta=access_token_expires)
return {"access_token": access_token, "token_type": "bearer"}
def create_access_token(data: dict, expires_delta: timedelta = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwtIn this setup, when a user logs in, a JWT token is issued. This token contains user information and an expiration time.
Step 2: Secure Routes with JWT in FastAPI
Next, secure your FastAPI routes by requiring a valid JWT for access.
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
except JWTError:
raise credentials_exception
return usernameThis function will be used to protect routes by verifying the token's authenticity and retrieving user information.
Step 3: Store and Use JWT in React
On the React side, we'll implement a context provider to store the authentication state.
// react_app/AuthContext.js
import React, { createContext, useState, useEffect } from 'react';
export const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [userToken, setUserToken] = useState(localStorage.getItem('userToken'));
const [user, setUser] = useState(null);
useEffect(() => {
if (userToken) {
// Decode token using jwt-decode or similar
const userInfo = decodeToken(userToken);
setUser(userInfo);
}
}, [userToken]);
const login = (token) => {
localStorage.setItem('userToken', token);
setUserToken(token);
};
const logout = () => {
localStorage.removeItem('userToken');
setUserToken(null);
setUser(null);
};
return (
{children}
);
};This context will manage the authentication state and allow components to access the current user.
Step 4: Protect React Routes and Make Authenticated Requests
Use React Router to protect routes that require authentication.
// react_app/ProtectedRoute.js
import React, { useContext } from 'react';
import { Route, Redirect } from 'react-router-dom';
import { AuthContext } from './AuthContext';
const ProtectedRoute = ({ component: Component, ...rest }) => {
const { user } = useContext(AuthContext);
return (
user ? (
) : (
)
}
/>
);
};
export default ProtectedRoute;Additionally, use the stored token to make authenticated requests.
// react_app/api.js
import axios from 'axios';
export const api = axios.create({
baseURL: 'http://localhost:8000',
});
api.interceptors.request.use(
config => {
const token = localStorage.getItem('userToken');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => Promise.reject(error)
);This configuration ensures that all requests include the JWT token, thus authenticating the user with the backend.
Common Errors/Troubleshooting
- Invalid Token Error: Ensure your token is correctly signed and not expired. Check the server's secret key and algorithm match the client's.
- Unauthorized Access: Check if the token is correctly attached to requests and if the protected routes are correctly set up in FastAPI.
- State Management Issues: Ensure the React context is properly configured and updates state upon login/logout.
Conclusion
By following these steps, you have successfully implemented JWT authentication in a React and FastAPI application. This approach secures your application and ensures a seamless user experience by managing authentication states efficiently.
Frequently Asked Questions
What is JWT?
JWT, or JSON Web Token, is a compact, URL-safe means of representing claims to be transferred between two parties. It is commonly used for authentication.
Why use JWT for authentication?
JWT allows for stateless, secure authentication, meaning you don't need to store session data on the server, making your applications more scalable.
How do I store a JWT in a React app?
JWTs can be stored in localStorage or sessionStorage in the browser, but localStorage is preferred for persistent user sessions.