JAVASCRIPT

Secure API Requests with Bearer Token Authentication

Learn to securely authenticate API requests using bearer tokens in JavaScript's Fetch API, sending authorization headers for protected endpoints.

async function fetchDataWithAuth(url, token) {
    try {
        const response = await fetch(url, {
            method: 'GET', // Or 'POST', 'PUT', 'DELETE'
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}` // Bearer token authentication
            }
        });

        if (!response.ok) {
            // Handle non-2xx responses
            const errorData = await response.json();
            throw new Error(`API Error: ${response.status} - ${errorData.message || response.statusText}`);
        }

        const data = await response.json();
        console.log('Fetched data:', data);
        return data;
    } catch (error) {
        console.error('Error fetching data with authentication:', error);
        throw error;
    }
}

// Example usage:
// const API_ENDPOINT = 'https://api.example.com/protected-data';
// const USER_TOKEN = 'your_jwt_or_oauth_token_here'; // Get this from login/auth process

// fetchDataWithAuth(API_ENDPOINT, USER_TOKEN)
//     .then(data => console.log('Successfully retrieved:', data))
//     .catch(err => console.error('Failed to retrieve data:', err));
How it works: This snippet demonstrates how to include a Bearer token in the Authorization header of your HTTP requests using JavaScript's Fetch API. Bearer tokens, often JSON Web Tokens (JWTs) or OAuth tokens, are a common method for authenticating clients with protected API endpoints. By sending `Authorization: Bearer [your_token]` in the request headers, you inform the server that the request is authorized, allowing access to resources that require authentication. This pattern is crucial for securing data and controlling access to sensitive API functionalities.

Need help integrating this into your project?

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

Hire DigitalCodeLabs