JAVASCRIPT

Making Authenticated API Requests with JWT in JavaScript

Learn how to include a JSON Web Token (JWT) in the Authorization header of your fetch API requests for secure, authenticated communication with backend services.

async function fetchWithAuth(url, options = {}) {
  const token = localStorage.getItem('authToken'); // Or from a cookie/session storage
  if (!token) {
    throw new Error('No authentication token found.');
  }

  const headers = {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`,
    ...options.headers,
  };

  try {
    const response = await fetch(url, { ...options, headers });
    if (!response.ok) {
      // Handle specific authentication errors, e.g., 401 Unauthorized
      if (response.status === 401) {
        console.error('Authentication failed. Please re-login.');
        // Optionally redirect to login page
        // window.location.href = '/login';
      }
      const errorData = await response.json().catch(() => ({ message: response.statusText }));
      throw new Error(`API error: ${response.status} ${errorData.message}`);
    }
    return await response.json();
  } catch (error) {
    console.error('Network or API request failed:', error);
    throw error;
  }
}

// Example Usage:
// Call this after a user logs in and you've stored the JWT.
// localStorage.setItem('authToken', 'YOUR_JWT_TOKEN_HERE');

// fetchWithAuth('/api/protected-data')
//   .then(data => console.log('Protected data:', data))
//   .catch(error => console.error('Failed to get protected data:', error));

// fetchWithAuth('/api/post-data', {
//   method: 'POST',
//   body: JSON.stringify({ item: 'new item' })
// })
//   .then(data => console.log('Posted data response:', data))
//   .catch(error => console.error('Failed to post data:', error));
How it works: This JavaScript snippet demonstrates how to make authenticated API requests using a JSON Web Token (JWT). It retrieves the JWT, typically stored in `localStorage` after a successful login, and includes it in the `Authorization` header of the `fetch` request using the `Bearer` scheme. The `fetchWithAuth` function wraps the standard `fetch` call, automatically adding the token and providing basic error handling for non-successful HTTP responses, including a specific check for 401 Unauthorized status.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs