Your Request's Passport

HTTP headers let you pass additional information alongside your request. The most common use: proving your identity to the server.

Bearer Token Authentication

When you log in, the server issues you an encrypted string called a token. You attach this token to every subsequent request.

const token = localStorage.getItem('auth_token');

const response = await fetch('/api/profile', {
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  }
});

Common Headers

HeaderPurpose
AuthorizationProve identity (Bearer tokens, API keys)
Content-TypeTell the server what format the request body is in
AcceptTell the server what format you want the response in
X-Request-IDCustom header for tracking requests

Creating a Reusable Authenticated Fetch

async function authFetch(url, options = {}) {
  const token = localStorage.getItem('auth_token');
  return fetch(url, {
    ...options,
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
      ...options.headers
    }
  });
}
Important

Never store sensitive tokens directly in source code you publish to GitHub. Use environment variables (.env files) to keep secrets out of version control.