Bearer tokens on requests

Once you have a token, every authenticated request needs to send it. The convention is an Authorization header with the value Bearer followed by the token. Do this once, in a wrapper function, and you never have to remember to add the header manually again.

api.js
javascript
import { getToken } from './auth';

export async function api(path, options = {}) {
  const token = getToken();
  const headers = {
    'Content-Type': 'application/json',
    ...options.headers,
  };
  if (token) headers.Authorization = 'Bearer ' + token;

  const res = await fetch(path, { ...options, headers });
  if (res.status === 401) {
    // token is missing, invalid, or expired
    window.location.href = '/login';
  }
  return res;
}

A single fetch wrapper that attaches the token on every call.

Notice what the api function does. It wraps fetch so every caller gets the token for free. Any 401 response triggers a redirect to the login page. One place handles token propagation, one place handles expiration. Never scatter this logic through your app.

Quiz: Quiz

Loading practice…