How to use JWT authentication in React
JWT authentication provides secure, stateless authentication for React applications by storing user credentials in tokens rather than server-side sessions. As the creator of CoreUI with extensive React experience since 2014, I’ve implemented JWT authentication in countless enterprise dashboard applications. The most effective approach combines React Context for global auth state with axios interceptors for automatic token attachment to requests. This pattern ensures secure authentication while providing seamless API communication throughout your application.
Create an authentication context that handles JWT tokens and automatically attaches them to API requests.
import { createContext, useContext, useState, useEffect } from 'react'
import axios from 'axios'
const AuthContext = createContext()
export function AuthProvider({ children }) {
const [token, setToken] = useState(localStorage.getItem('token'))
const [user, setUser] = useState(null)
useEffect(() => {
if (token) {
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
// Verify token and get user data
fetchUser()
}
}, [token])
const login = async (credentials) => {
const response = await axios.post('/api/login', credentials)
const { token: newToken, user } = response.data
localStorage.setItem('token', newToken)
axios.defaults.headers.common['Authorization'] = `Bearer ${newToken}`
setToken(newToken)
setUser(user)
}
const logout = () => {
localStorage.removeItem('token')
delete axios.defaults.headers.common['Authorization']
setToken(null)
setUser(null)
}
return (
<AuthContext.Provider value={{ token, user, login, logout }}>
{children}
</AuthContext.Provider>
)
}
export const useAuth = () => useContext(AuthContext)
This code creates an authentication context that manages JWT tokens in localStorage and automatically configures axios to include the Bearer token in all requests. The login function stores the token and sets up the authorization header, while logout cleans up all authentication data. The useEffect ensures tokens persist across browser sessions.
Best Practice Note:
This is the JWT authentication architecture we use in CoreUI Pro dashboard templates for enterprise security. Consider implementing token refresh logic and secure httpOnly cookie storage for production applications with enhanced security requirements.



