Mastering Interceptors and Auth Guards in JavaScript & React

Interceptors and auth guards are two of the most frequently asked interview questions. When building modern web applications, security and efficient request handling are crucial. Interceptors and authentication guards help manage API requests, handle authentication, and protect routes. In this article, we’ll explore how to implement Interceptors and Auth Guards in a React application.

1. What Are Interceptors?

Interceptors allow us to modify HTTP requests or responses before they reach the server or client. In React applications, we commonly use Axios interceptors to:

  • Attach authentication tokens to API requests.
  • Handle errors globally (like unauthorized access or server errors).
  • Modify responses before they reach the components.

Axios Interceptors Example

Let’s set up an Axios interceptor to attach an authentication token to every API request.

import axios from "axios";

// Create an Axios instance
const api = axios.create({
  baseURL: "https://api.example.com",
  headers: {
    "Content-Type": "application/json",
  },
});

// Request Interceptor (Attach Token)
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("authToken");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Response Interceptor (Handle Errors)
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      console.error("Unauthorized! Redirecting to login...");
      window.location.href = "/login";
    }
    return Promise.reject(error);
  }
);

export default api;

How It Works

  1. Request Interceptor:
    • Retrieves the authentication token from localStorage.
    • Attaches it to every outgoing request.
  2. Response Interceptor:
    • If the server returns a 401 Unauthorized response, it redirects the user to the login page.

2. What Are Authentication Guards?

Authentication guards (or Route Guards) protect certain routes in your application. For example, you might want to restrict access to the dashboard unless the user is logged in.

Implementing an Auth Guard in React Router

React Router allows us to create protected routes easily.

Creating an Auth Guard (Protected Route)

import React from "react";
import { Navigate, Outlet } from "react-router-dom";

const ProtectedRoute = () => {
  const isAuthenticated = localStorage.getItem("authToken"); // Check if token exists
  return isAuthenticated ? <Outlet /> : <Navigate to="/login" />;
};

export default ProtectedRoute;

Using Auth Guard in React Router

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Home from "./pages/Home";
import Dashboard from "./pages/Dashboard";
import Login from "./pages/Login";
import ProtectedRoute from "./components/ProtectedRoute";

const App = () => {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/login" element={<Login />} />
        
        {/* Protect Dashboard Route */}
        <Route element={<ProtectedRoute />}>
          <Route path="/dashboard" element={<Dashboard />} />
        </Route>
      </Routes>
    </Router>
  );
};

export default App;

How It Works

  1. ProtectedRoute checks if the user is authenticated.
  2. If authenticated, it renders the requested page (<Outlet />).
  3. If not, it redirects the user to the /login page.

3. Combining Interceptors & Auth Guards

By combining Axios interceptors and authentication guards, we ensure:

  • Every API request is authenticated.
  • Unauthorized users are redirected to login.
  • Secure pages (like Dashboard) remain protected.

Example Flow

  1. User visits /dashboardProtectedRoute checks for an auth token.
  2. If no token → User is redirected to /login.
  3. User logs in → Token is stored → API requests now include the token.
  4. If an API request returns 401 → User is logged out automatically.

Conclusion

  • Interceptors help attach tokens and handle global errors.
  • Auth Guards protect pages from unauthorized access.
  • Using both ensures a secure and smooth user experience.