Vanilla JavaScript JWT Auth

Implement JWT authentication in vanilla JavaScript with token storage in localStorage, automatic token attachment to fetch requests, expiry checking, and.

Javascript Auth Jwt

Code

snippet
const TOKEN_KEY = 'auth_token';

export const auth = {
  getToken: () => localStorage.getItem(TOKEN_KEY),
  setToken: (t) => localStorage.setItem(TOKEN_KEY, t),
  clear: () => localStorage.removeItem(TOKEN_KEY),
  isExpired: (t) => {
    const payload = JSON.parse(atob(t.split('.')[1]));
    return Date.now() >= payload.exp * 1000;
  },
  fetchWithAuth: async (url, opts = {}) => {
    const token = auth.getToken();
    const res = await fetch(url, {
      ...opts,
      headers: { ...opts.headers, Authorization: `Bearer ${token}` },
    });
    if (res.status === 401) location.href = '/login';
    return res;
  },
};