Vanilla JavaScript JWT Auth

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

JavascriptAuth Jwt

Code

javascriptsnippet
20 lines
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;
  },
};

Inside the snippet

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Module-level bindings hold the data — TOKEN_KEY — with no function scope in between.

Points of care

  • A browser is the runtime here: localStorage, fetch are not available in Node.

Putting it to use

The main signature reads export const auth =

auth is what another module would consume; nothing else here is load-bearing for callers.

Core lines

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;
},
return Date.now() >= payload.exp * 1000;

Interactive Tools for This Topic

FAQ

Does Vanilla JavaScript JWT Auth run in plain Node.js?
No — it touches `localStorage`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.