Vanilla JavaScript JWT Auth
Implement JWT authentication in vanilla JavaScript with token storage in localStorage, automatic token attachment to fetch requests, expiry checking, and.
Code
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,fetchare 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
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.JWT Token DecoderDecode JSON Web Token (JWT) headers and payloads safely in the browser. Inspect expiration, issuer, and claims without sending tokens to any external server.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.