MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
JWT Authentication Flow and Silent Token Refresh0%
Study Materials
React.js for AdvancedProgress 0%
1.1Control Props and Inversion of Control Pattern1.2State Reducer Pattern in Advanced React1.3Prop Getters and Flexible Design Systems1.4Headless UI Architecture and Accessibility Primitives
10.1JWT Authentication Flow and Silent Token Refresh10.2OAuth2 and Social Login Integration10.3Role-Based Access Control (RBAC) and Permission Matrices10.4Securing Client-Side Storage and CSRF / XSS Mitigation
HomeTutorialsReact.js for AdvancedJWT Authentication Flow and Silent Token Refresh
OAuth2 and Social Login Integration

JWT Authentication Flow and Silent Token Refresh

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

JSON Web Tokens (JWT) are the industry standard for stateless authentication in modern web applications. An enterprise authentication architecture requires a two-token system: short-lived Access Tokens (held in memory) and long-lived Refresh Tokens (stored in httpOnly, SameSite=Strict cookies) with automated silent token rotation via Axios or fetch interceptors.


1. The Two-Token Architecture

Storing access tokens in localStorage or sessionStorage exposes user credentials to Cross-Site Scripting (XSS) theft. Storing tokens exclusively in plain cookies exposes them to Cross-Site Request Forgery (CSRF).

1Enterprise Dual-Token Architecture:
2┌────────────────────────┐ ┌────────────────────────┐
3│ Client (React App) │ │ Auth Backend (Node/DJ) │
4└──────────┬─────────────┘ └───────────┬────────────┘
5 │ 1. POST /api/auth/login │
6 ├─────────────────────────────────────────────►│
7 │ 2. Returns: AccessToken (in JSON body) │
8 │ Sets: httpOnly RefreshToken cookie │
9 │◄─────────────────────────────────────────────┤
10 │ │
11 │ 3. Authenticated API call with Bearer Token │
12 ├─────────────────────────────────────────────►│
13 │ │
14 │ 4. 401 Unauthorized (AccessToken expired) │
15 │◄─────────────────────────────────────────────┤
16 │ │
17 │ 5. POST /api/auth/refresh (cookie attached) │
18 ├─────────────────────────────────────────────►│
19 │ 6. Returns new AccessToken │
20 │◄─────────────────────────────────────────────┤
21 │ │
22 │ 7. Replays original failed API request │
23 ├─────────────────────────────────────────────►│

2. Axios Silent Refresh Interceptor

An enterprise Axios interceptor detects 401 Unauthorized responses, queues pending outgoing requests, executes a silent refresh, and retries the original request seamlessly without logging the user out:

1// api/client.ts
2import axios, { AxiosError, InternalAxiosRequestConfig } from "axios";
3 
4export const apiClient = axios.create({
5 baseURL: "https://api.enterprise.com/v1",
6 withCredentials: true, // Crucial: automatically includes httpOnly refresh cookies
7});
8 
9// In-memory access token storage (isolated from XSS access to localStorage)
10let memoryAccessToken: string | null = null;
11 
12export const setAccessToken = (token: string | null) => {
13 memoryAccessToken = token;
14};
15 
16// Request Interceptor: Injects Bearer token into headers
17apiClient.interceptors.request.use((config: InternalAxiosRequestConfig) => {
18 if (memoryAccessToken && config.headers) {
19 config.headers.Authorization = `Bearer ${memoryAccessToken}`;
20 }
21 return config;
22});
23 
24// Response Interceptor: Silent Token Refresh Queue
25let isRefreshing = false;
26let failedQueue: Array<{
27 resolve: (value?: unknown) => void;
28 reject: (reason?: any) => void;
29}> = [];
30 
31const processQueue = (error: AxiosError | null, token: string | null = null) => {
32 failedQueue.forEach((prom) => {
33 if (error) {
34 prom.reject(error);
35 } else {
36 prom.resolve(token);
37 }
38 });
39 failedQueue = [];
40};
41 
42apiClient.interceptors.response.use(
43 (response) => response,
44 async (error: AxiosError) => {
45 const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean };
46 
47 // Detect 401 and avoid infinite loops
48 if (error.response?.status === 401 && !originalRequest._retry) {
49 if (isRefreshing) {
50 // Another request is already refreshing; queue this request
51 return new Promise((resolve, reject) => {
52 failedQueue.push({ resolve, reject });
53 })
54 .then((token) => {
55 originalRequest.headers.Authorization = `Bearer ${token}`;
56 return apiClient(originalRequest);
57 })
58 .catch((err) => Promise.reject(err));
59 }
60 
61 originalRequest._retry = true;
62 isRefreshing = true;
63 
64 try {
65 // Silent refresh request (cookie sent automatically via withCredentials)
66 const refreshResponse = await axios.post<{ accessToken: string }>(
67 "https://api.enterprise.com/v1/auth/refresh",
68 {},
69 { withCredentials: true }
70 );
71 
72 const newAccessToken = refreshResponse.data.accessToken;
73 setAccessToken(newAccessToken);
74 
75 processQueue(null, newAccessToken);
76 
77 originalRequest.headers.Authorization = `Bearer ${newAccessToken}`;
78 return apiClient(originalRequest);
79 } catch (refreshError) {
80 processQueue(refreshError as AxiosError, null);
81 setAccessToken(null);
82 // Force redirect to login page on refresh token invalidation
83 window.location.href = "/login?expired=true";
84 return Promise.reject(refreshError);
85 } finally {
86 isRefreshing = false;
87 }
88 }
89 
90 return Promise.reject(error);
91 }
92);

3. Auth Context Provider

Wrap your application in an AuthProvider that initiates a silent refresh on initial application mount:

1import React, { createContext, useContext, useEffect, useState } from "react";
2import { apiClient, setAccessToken } from "./client";
3 
4interface AuthContextValue {
5 isAuthenticated: boolean;
6 isLoading: boolean;
7 login: (token: string) => void;
8 logout: () => Promise<void>;
9}
10 
11const AuthContext = createContext<AuthContextValue | null>(null);
12 
13export function AuthProvider({ children }: { children: React.ReactNode }) {
14 const [isAuthenticated, setIsAuthenticated] = useState(false);
15 const [isLoading, setIsLoading] = useState(true);
16 
17 useEffect(() => {
18 // Initial mount: check if refresh cookie exists by performing silent refresh
19 apiClient
20 .post<{ accessToken: string }>("/auth/refresh")
21 .then((res) => {
22 setAccessToken(res.data.accessToken);
23 setIsAuthenticated(true);
24 })
25 .catch(() => {
26 setIsAuthenticated(false);
27 })
28 .finally(() => {
29 setIsLoading(false);
30 });
31 }, []);
32 
33 const login = (token: string) => {
34 setAccessToken(token);
35 setIsAuthenticated(true);
36 };
37 
38 const logout = async () => {
39 await apiClient.post("/auth/logout");
40 setAccessToken(null);
41 setIsAuthenticated(false);
42 };
43 
44 return (
45 <AuthContext.Provider value={{ isAuthenticated, isLoading, login, logout }}>
46 {!isLoading && children}
47 </AuthContext.Provider>
48 );
49}
50 
51export const useAuth = () => {
52 const ctx = useContext(AuthContext);
53 if (!ctx) throw new Error("useAuth must be used within AuthProvider");
54 return ctx;
55};

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
Why is storing JWT Access Tokens in localStorage considered an enterprise security vulnerability?
Question 2
Why should Refresh Tokens be stored in httpOnly, SameSite=Strict cookies?
Question 3
What is the function of the failedQueue array in the Axios response interceptor?
Question 4
What does withCredentials: true configure in Axios?
Question 5
What should happen when the /auth/refresh endpoint itself returns a 401 or 403 error?
Next Lesson

OAuth2 and Social Login Integration

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Polymorphic Component Typing with As and ComponentPropsWithoutRefOAuth2 and Social Login Integration

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext