JAVASCRIPT

Authenticate with OAuth 2.0 Client Credentials Grant in Node.js

Securely access third-party APIs from your backend using the OAuth 2.0 Client Credentials Grant, ideal for server-to-server communication without requiring user interaction.

const clientId = 'YOUR_CLIENT_ID';
const clientSecret = process.env.CLIENT_SECRET; // Store securely (e.g., environment variable)
const tokenUrl = 'https://api.example.com/oauth/token'; // Your API's token endpoint
const apiUrl = 'https://api.example.com/data'; // Protected resource API

async function getAccessToken() {
    try {
        const credentials = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');

        const response = await fetch(tokenUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': `Basic ${credentials}`
            },
            body: 'grant_type=client_credentials'
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(`Failed to get access token: ${response.status} - ${errorData.error_description || errorData.error}`);
        }

        const data = await response.json();
        return data.access_token;

    } catch (error) {
        console.error('Error fetching access token:', error.message);
        throw error;
    }
}

async function callProtectedApi() {
    try {
        const accessToken = await getAccessToken();
        console.log('Access Token obtained:', accessToken);

        const response = await fetch(apiUrl, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${accessToken}`
            }
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(`Failed to call protected API: ${response.status} - ${errorData.message || 'Unknown error'}`);
        }

        const apiData = await response.json();
        console.log('Protected API Data:', apiData);
        return apiData;

    } catch (error) {
        console.error('Error calling protected API:', error.message);
        throw error;
    }
}

// Example usage:
// (async () => {
//     await callProtectedApi();
// })();
How it works: This Node.js snippet demonstrates how to implement the OAuth 2.0 Client Credentials Grant flow for server-to-server API authentication. This flow is used when your application needs to access an API on its own behalf, without the context of an end-user. It involves exchanging a `client_id` and `client_secret` (which should be stored securely, ideally as environment variables) for an `access_token` from the authorization server's token endpoint. This token is then included in the `Authorization` header of subsequent requests to access protected API resources, ensuring secure and authorized backend integrations.

Need help integrating this into your project?

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

Hire DigitalCodeLabs