How to protect API requests in React

Protecting API requests in React ensures that sensitive endpoints require proper authentication and handle unauthorized access gracefully. As the creator of CoreUI with extensive React experience since 2014, I’ve implemented API request protection in numerous enterprise applications for secure data access. The most effective approach uses axios interceptors to automatically attach authentication tokens and handle token refresh scenarios. This method provides centralized request protection while maintaining clean component code and consistent error handling.

Use axios interceptors to automatically attach authentication tokens to API requests and handle unauthorized responses.

import axios from 'axios'

// Create axios instance with base configuration
const apiClient = axios.create({
    baseURL: process.env.REACT_APP_API_URL
})

// Request interceptor to add auth token
apiClient.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('authToken')
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    (error) => Promise.reject(error)
)

// Response interceptor to handle unauthorized responses
apiClient.interceptors.response.use(
    (response) => response,
    (error) => {
        if (error.response?.status === 401) {
            localStorage.removeItem('authToken')
            window.location.href = '/login'
        }
        return Promise.reject(error)
    }
)

// Usage in components
export const fetchUserData = async () => {
    try {
        const response = await apiClient.get('/user/profile')
        return response.data
    } catch (error) {
        throw error
    }
}

This code creates an axios instance with interceptors that automatically add Bearer tokens to requests and handle 401 unauthorized responses by redirecting to login. The request interceptor checks for stored tokens and adds them to headers, while the response interceptor catches authentication failures and performs cleanup. This ensures all API calls are automatically protected without manual token management in components.

Best Practice Note:

This is the API security pattern we use in CoreUI Pro dashboard applications for enterprise-grade request protection. Consider implementing token refresh logic in the response interceptor to handle expired tokens gracefully without forcing re-login.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team