Login, logout, and token expiry

The full token lifecycle is four steps. Login posts credentials and gets a token. Save sends the token to storage. Every request reads the token and attaches it. Logout clears it. Expiry is a special case of logout that the server forces.

auth.js
javascript
import { api } from './api';
import { saveToken, clearToken } from './auth';

export async function login(username, password) {
  const res = await api('/api/auth/login', {
    method: 'POST',
    body: JSON.stringify({ username, password }),
  });
  if (!res.ok) throw new Error('Invalid credentials');
  const { token } = await res.json();
  saveToken(token);
  return token;
}

export function logout() {
  clearToken();
  window.location.href = '/login';
}

The full login and logout flow from the client side.

Tokens expire. The api wrapper from earlier catches 401 responses and redirects to login, which is usually enough for a self-paced app. For longer sessions, you can add refresh tokens: a second, longer-lived token that lets you get a new access token without asking the user to log in again. Start simple. Add refresh tokens only when the UX demands it.

Quiz: Quiz

Loading practice…