SkillPilotAI

Axios and the API layer

An API layer is one central place every HTTP call passes through: an Axios instance with baseURL and timeout, interceptors that add the token and refresh it on 401, one error-normalizing function and endpoint functions like ordersApi.list().

50.1 Why is it used?

  • With fetch everywhere, every call repeats the base URL, the token header and the error check.
  • The one place you forget becomes a bug: getOrders skipped res.ok, so a 401 body was treated as orders.
  • fetch does not throw on 401/500.
  • If the API URL or token format changes you must edit every file.
JavaScript
import { authHeader } from "./auth"; export async function getProducts() {  const res = await fetch("/api/products");  if (!res.ok) throw new Error(res.status);  return res.json();} export async function getOrders() {  const res = await fetch("/api/orders", {    headers: { Authorization: authHeader() },  });  return res.json();}console.log(await getOrders());
Output
> { message: 'Token expired' }Screen: the error was treated as orders
What goes wrong with fetch everywhere
  1. 1.Base URL hardcoded in every file

  2. 2.Token header added by hand in each call

  3. 3.Error check sometimes, not always

  4. 4.401 body treated as data

Fix: one API layer every call passes through

50.2 Axios basics

  • params: { page: 2 } builds the query string for you.
  • res.data is already parsed JSON.
  • post(url, body): the body is sent as JSON automatically.
  • Axios throws for error statuses (401, 500), so catch gets err.response.status.
Terminal
npm install axios
JavaScript
import axios from "axios"; const res = await axios.get("/api/products", {  params: { page: 2 },});console.log(res.data); await axios.post("/api/cart", { id: 7 }); try {  await axios.get("/api/orders");} catch (err) {  console.log(err.response.status);}
Output
-- after get --> [ 'Phone', 'Laptop' ] -- after the failing get --> [ 'Phone', 'Laptop' ]> 401

50.3 Axios instance and request interceptor

  • axios.create builds a separate axios object with common config: baseURL from an env variable (VITE_API_URL) and a 10 second timeout.
  • Then anywhere in the app: api.get("/products").
  • A request interceptor is like an airport security check: every request passes through it before going to the server.
  • It reads the current token and sets Authorization: Bearer <token>; returning config is required.
JavaScript
import axios from "axios";import { getToken } from "./auth"; export const api = axios.create({  baseURL: import.meta.env.VITE_API_URL,  timeout: 10000,});api.interceptors.request.use((config) => {  const token = getToken();  if (token) {    config.headers.Authorization =      `Bearer ${token}`;  }  return config;});
Output
-- server log --GET /api/products 200Authorization: Bearer abc123

50.4 Response interceptor: token refresh

  • Access tokens are short lived; on expiry the server sends 401, but the user should not log in again.
  • First function passes successful responses through; the second runs on errors.
  • On 401 for a request not yet retried: set req._retry = true, call refreshToken(), then return api(req) to resend the same request.
  • Anything else: Promise.reject(error).
JavaScript
import { api } from "./api";import { refreshToken } from "./auth";api.interceptors.response.use(  (res) => res,  async (error) => {    const req = error.config;    const status = error.response?.status;    if (status === 401 && !req._retry) {      req._retry = true;      await refreshToken();      return api(req);    }    return Promise.reject(error);  });
Output
-- token expired --GET /api/orders 401 -- refresh called --GET /api/orders 401POST /api/auth/refresh 200 -- original request retried --GET /api/orders 401POST /api/auth/refresh 200GET /api/orders 200
The token refresh flow
  1. 1.Component calls api: request interceptor adds the token

  2. 2.Server checks the token: expired, returns 401

  3. 3.Response interceptor calls refresh, gets a new token

  4. 4.Original request retried with the new token

  5. 5.Component gets the data, never knowing what happened

_retry flag prevents an infinite loop

50.5 Checkpoint: interceptor without return

  • The interceptor sets the header but forgets return config.
  • Result: the request never reaches the server and catch gets a confusing error.
  • Whatever the interceptor returns is what moves forward, so always return config.
JavaScript
import axios from "axios"; const api = axios.create({  baseURL: import.meta.env.VITE_API_URL,});api.interceptors.request.use((config) => {  config.headers.Authorization = "Bearer abc";}); try {  await api.get("/products");} catch (err) {  console.log(err.message);}
Output
Cannot read properties of undefined (reading 'cancelToken')Screen: no request reached the server

50.6 Error handling: three cases

CaseHow to detectMessage shown
Server replied with an error statuserr.response existsServer message (e.g. Out of stock) or Error <status>
Timeouterr.code === "ECONNABORTED"Request timed out
No reply at allNo err.responseNetwork error, check internet
Not an Axios error!axios.isAxiosError(err)Something went wrong
JavaScript
import axios from "axios"; export function getErrorMessage(err) {  if (!axios.isAxiosError(err)) {    return "Something went wrong";  }  if (err.response) {    return err.response.data?.message      ?? `Error ${err.response.status}`;  }  if (err.code === "ECONNABORTED") {    return "Request timed out";  }  return "Network error, check internet";}
Output
-- server error (err.response) --> Out of stock -- timeout --> Out of stock> Request timed out -- no reply --> Out of stock> Request timed out> Network error, check internet

50.7 API layer: ordersApi

  • All endpoints become functions in one file; a small data helper returns only res.data.
  • Components and TanStack Query queryFns call ordersApi.list() instead of writing URLs.
  • If an endpoint changes, only this file changes.
JavaScript
import { api } from "./api"; const data = (res) => res.data; export const ordersApi = {  list: (params) =>    api.get("/orders", { params }).then(data),  get: (id) =>    api.get(`/orders/${id}`).then(data),  create: (body) =>    api.post("/orders", body).then(data),}; // queryFn: () => ordersApi.list({ page: 1 })
Output
> [ { id: 1 }, { id: 2 } ]

50.8 Comparison: fetch vs Axios

PointfetchAxios
AvailabilityBuilt into the browserLibrary (npm install axios)
JSONCall res.json() yourselfres.data already parsed, body sent as JSON
Error statusesDoes not throw on 401/500; check res.okThrows; err.response.status
InterceptorsNo (write a wrapper)request / response interceptors
TimeoutVia AbortControllertimeout option

50.9 Common mistakes

  • Setting the token in headers when creating the instance: that line runs once at app load, before login, so every request sends Bearer null.
  • Fix: read the current token in a request interceptor on every request.
  • Forgetting return config in a request interceptor.
  • Refreshing through the same api instance, which can loop through the interceptor; use plain axios for the refresh call.
  • Myth: fetch is old and every project needs Axios. fetch is fine; the real point is the API layer, which can also wrap fetch.
JavaScript
import axios from "axios";import { getToken } from "./auth"; const auth = `Bearer ${getToken()}`;export const api = axios.create({  baseURL: import.meta.env.VITE_API_URL,  headers: { Authorization: auth },});
JavaScript
import axios from "axios";import { getToken } from "./auth"; export const api = axios.create({  baseURL: import.meta.env.VITE_API_URL,});api.interceptors.request.use((config) => {  config.headers.Authorization =    `Bearer ${getToken()}`;  return config;});

50.10 Best practices

  • One api instance for the whole app: env baseURL plus a timeout.
  • No hardcoded URLs in components; call the service layer.
  • Token in an interceptor; refresh call with plain axios.
  • Normalize errors in one function.

50.11 Interview tips

  • Interceptors are functions that run before every request and after every response.
  • Request interceptor adds the access token; response interceptor catches 401, refreshes and retries the original request.
  • A _retry flag stops an infinite loop; many simultaneous 401s should share one refresh promise.
  • Axios throws on error statuses, fetch does not; either way, put calls behind an API layer.