API Keys & Bearer Tokens
Authenticating requests with API keys, JWT Bearer tokens, and keeping secrets safe
Skills taught: api.api-key-header, api.bearer-token, api.basic-auth, api.token-storage
Authentication patterns
// ── API Key (server-to-server) ──
// Many APIs accept key in Authorization header or custom header
const OPENAI_KEY = process.env.OPENAI_API_KEY; // never hardcode!
const res = await fetch('https://api.openai.com/v1/models', {
headers: {
'Authorization': `Bearer ${OPENAI_KEY}`, // OpenAI uses Bearer
},
});
// Some APIs use a custom header:
const weather = await fetch('https://api.openweathermap.org/data/2.5/weather?q=London', {
headers: { 'x-api-key': process.env.WEATHER_KEY },
});
// Some APIs accept it as a query param (avoid — appears in logs):
// fetch(`...?appid=${key}`) ← use header instead when available
// ── Login → Bearer Token flow ──
async function login(email, password) {
const res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
if (!res.ok) throw new Error('Invalid credentials');
const { token, refreshToken } = await res.json();
// Store token — in memory for security, localStorage for persistence
sessionStorage.setItem('token', token);
return token;
}
// ── Authenticated request helper ──
function authFetch(url, options = {}) {
const token = sessionStorage.getItem('token');
return fetch(url, {
...options,
headers: {
...options.headers,
'Authorization': token ? `Bearer ${token}` : undefined,
'Content-Type': 'application/json',
},
});
}
// Usage:
const profile = await authFetch('/api/users/me').then(r => r.json());
// ── Decode JWT payload (client-side preview only) ──
function decodeToken(jwt) {
const [, payload] = jwt.split('.');
return JSON.parse(atob(payload.replace(/-/g,'+').replace(/_/g,'/')));
}
// → { sub: 'user42', exp: 1752345678, iat: 1752259278, role: 'admin' }
// NOTE: This is NOT verification — trust only what your server tells you
Tip: Never include API keys or tokens in frontend source code that ships to browsers. Store them in environment variables on your backend server, and have the frontend call YOUR backend, which proxies to the third-party API.
Frequently Asked Questions
What is a JWT and how do I use it?
JWT (JSON Web Token) is a self-contained token with three dot-separated base64url parts: header (algorithm), payload (claims like user ID and expiry), and signature. After login, your server creates and signs a JWT and sends it to the client. The client includes it in every request: `Authorization: Bearer <token>`. The server verifies the signature to confirm authenticity — no database lookup needed. Decode the payload client-side with `JSON.parse(atob(token.split('.')[1]))` to read claims like the user's name, but never trust client-side decoding for security decisions.