← Back to all snippets
JAVASCRIPT

Obtain OAuth 2.0 Access Token Using Client Credentials Grant

Securely fetch an access token from an OAuth 2.0 provider using the client credentials grant type for server-to-server API authentication in Node.js.

const fetch = require('node-fetch');

async function getClientCredentialsToken(tokenUrl, clientId, clientSecret, scope = '') {
  try {
    const authString = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
    const params = new URLSearchParams();
    params.append('grant_type', 'client_credentials');
    if (scope) {
      params.append('scope', scope);
    }

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

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`Failed to get token: ${response.status} - ${errorText}`);
    }

    const data = await response.json();
    return data.access_token;
  } catch (error) {
    console.error('Error fetching client credentials token:', error);
    throw error;
  }
}

// Usage example:
// const TOKEN_URL = 'https://api.example.com/oauth/token';
// const CLIENT_ID = 'your_client_id';
// const CLIENT_SECRET = 'your_client_secret';
// const SCOPE = 'read:data write:data'; // Optional scope

// (async () => {
//   try {
//     const accessToken = await getClientCredentialsToken(TOKEN_URL, CLIENT_ID, CLIENT_SECRET, SCOPE);
//     console.log('Access Token:', accessToken);
//     // Use accessToken to make subsequent API calls
//   } catch (error) {
//     console.error('Application failed to authenticate:', error);
//   }
// })();
How it works: This snippet demonstrates how to obtain an OAuth 2.0 access token using the Client Credentials grant type. This flow is ideal for server-to-server communication where an application needs to access an API without a user's direct involvement. It sends the client ID and secret, base64-encoded, in the Authorization header to the token endpoint to receive an access token, which can then be used for authenticated API requests.

Need help integrating this into your project?

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

Hire DigitalCodeLabs