DocsGuidesToken Refresh
Guide: Token Refresh & Axios Interceptors
Implement seamless, silent JWT token renewal with Axios interceptors in React and Next.js applications.
Security & Token Rotation
VeriLens uses rotating refresh tokens. Each call to `/api/v1/auth/refresh` immediately invalidates the submitted refresh token and returns a new pair. If an expired or already-used token is received, the server assumes token theft and terminates all sessions.
Production Axios Interceptor Setup
Attach your access token automatically and intercept 401 Unauthorized responses to perform a single-flight token renewal:
typescript/apiClient.ts
import axios from 'axios';const api = axios.create({baseURL: 'https://api.verilens.id/api/v1',headers: { 'Content-Type': 'application/json' }});// 1. Attach access token to outgoing requestsapi.interceptors.request.use((config) => {const token = localStorage.getItem('access_token');if (token && config.headers) {config.headers.Authorization = `Bearer ${token}`;}return config;});// 2. Intercept 401s and refresh token silentlyapi.interceptors.response.use((response) => response,async (error) => {const originalRequest = error.config;if (error.response?.status === 401 && !originalRequest._retry) {originalRequest._retry = true;const refreshToken = localStorage.getItem('refresh_token');if (!refreshToken) {window.location.href = '/login';return Promise.reject(error);}try {const { data } = await axios.post('https://api.verilens.id/api/v1/auth/refresh', {refresh_token: refreshToken});localStorage.setItem('access_token', data.access_token);localStorage.setItem('refresh_token', data.refresh_token);originalRequest.headers.Authorization = `Bearer ${data.access_token}`;return api(originalRequest);} catch (refreshError) {localStorage.removeItem('access_token');localStorage.removeItem('refresh_token');window.location.href = '/login';return Promise.reject(refreshError);}}return Promise.reject(error);});export default api;
