In this article
July 11, 2025
July 11, 2025

How to add auth to your Node.js CLI using WorkOS

Authenticate users in your Node.js command-line tool with a secure OAuth 2.0 Device Code flow using WorkOS. This tutorial shows how to implement login via the terminal, step by step.

Modern CLI apps often need to authenticate users — and using a simple web-based OAuth flow is the cleanest way to do it.

In this tutorial, we’ll implement a CLI login flow using WorkOS CLI Auth to authenticate users from the command line by using a web browser. Based on the OAuth 2.0 Device Authorization Grant, this method is perfect for CLIs where embedding a browser isn't feasible.

In this guide, we’ll walk through how to add auth to your Node.js CLI using WorkOS, step by step.

What we will build

You’ll create a Node.js CLI that:

  1. Requests a device code from WorkOS: The CLI starts the login flow by contacting WorkOS to get a device_code (for itself) and a user_code (for the user), along with a URL the user should visit.
  2. Displays a user-friendly prompt: The CLI prints the user_code and verification URL in the terminal, and optionally opens the browser automatically for the user to log in and approve.
  3. Polls WorkOS while the user logs in: As the user completes authentication in the browser, the CLI quietly checks in with WorkOS every few seconds to see if the user has completed the login.
  4. Exchanges the device code for tokens: Once authorized, the CLI receives an access token ready to make authenticated API calls.

This flow is ideal for tools running in environments that can’t easily embed a browser window (like the terminal), and it avoids the need to paste auth tokens manually.

Let’s dive in.

Prerequisites

Before starting, make sure you have:

Step 1: Start the auth flow from the CLI

Start by initiating the device authorization flow from your CLI tool. This will generate a user-facing code and a verification URL.

	
function requestDeviceCode(){
  const response = await fetch(
    'https://api.workos.com/user_management/authorize/device',
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: new URLSearchParams({
        client_id: 'APP_CLIENT_ID',
      }),
    },
  );

  const data = await response.json();
}
	

This function hits the WorkOS Device Authorization endpoint and retrieves:

  • device_code: For your CLI only.
  • user_code: To show the user.
  • verification_uri_complete: A URL users can click to authorize.
  • interval: How often to poll for the token.
	
{
  "device_code": "71azDp28ToiCscGDvLxnXLkuuFRMrnd4V7rdsjIlBPXuy13j8GOzU0aZHb46tsz3",
  "user_code": "RRGQ-BJVS",
  "verification_uri": "https://smart-chefs.authkit.app/device",
  "verification_uri_complete": "https://smart-chefs.authkit.app/device?user_code=ABCD-EFGH",
  "expires_in": 300,
  "interval": 5
}
	

Step 2: Prompt the user to authenticate

Display the user code and link in the terminal. Optionally, open the browser automatically.

	
function promptUserToAuthenticate(data) {
  console.log('\nTo sign in');
  console.log(`\nVisit: ${verification_uri}`);
  console.log(`Enter code: ${user_code}\n`);
  console.log(`Or open: ${verification_uri_complete}`);
    
  await open(verification_uri_complete);
}
	

Note the following:

  • Always display the user_code and verification_uri to the user.
  • Never show the device_code, it’s only used internally for polling.

Step 3: Poll for access tokens

While the user authenticates in their browser, your app should poll the token endpoint.

	
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function pollForTokens({
  clientId,
  deviceCode,
  expiresIn = 300,
  interval = 5,
}) {
  const timeout = AbortSignal.timeout(expiresIn * 1000);

  while (true) {
    const response = await (async () => {
      try {
        return await fetch(
          'https://api.workos.com/user_management/authenticate',
          {
            method: 'POST',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
              grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
              device_code: deviceCode,
              client_id: clientId,
            }),
            signal: timeout,
          },
        );
      } catch (error) {
        if (error.name === 'TimeoutError') {
          throw new Error('Authorization timed out');
        }
        throw error;
      }
    })();

    const data = await response.json();

    if (response.ok) {
      // Success! Return tokens for further processing.
      return data;
    }

    switch (data.error) {
      case 'authorization_pending':
        // Wait before polling again
        await sleep(interval * 1000);
        break;

      case 'slow_down':
        // You shouldn't see this if you're only polling every 5 seconds.
        // In this example, we're increasing the interval by 1 second when this happens.
        interval += 1;
        await sleep(interval * 1000);
        break;

      // Terminal cases
      case 'access_denied':
      case 'expired_token':
        throw new Error('Authorization failed');

      default:
        throw new Error('Authorization failed');
    }
  }
}
	

Note the following:

  • Poll at the interval specified in the authorization response (every 5 seconds).
  • Respect slow_down errors by increasing your polling interval.
  • Stop polling when you receive access_denied or expired_token errors.
  • Implement a reasonable timeout to avoid infinite polling.

The response looks like this:

	
{
  "user": {
    "object": "user",
    "id": "user_01JYHX0DW7077GPTAY8MZVNMQX",
    "email": "grant.mccode@workos.com",
    "email_verified": true,
    "first_name": "Grant",
    "last_name": "McCode",
    "profile_picture_url": null,
    "last_sign_in_at": "2025-06-25T19:16:35.647Z",
    "created_at": "2025-06-25T01:20:21.355Z",
    "updated_at": "2025-06-25T19:16:35.647Z",
    "external_id": null
  },
  "organization_id": "org_01JYHNPKWTD5DRGPJHNYBB1HB8",
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkdyYW50IE1jQ29kZSIsImFkbWluIjp0cnVlLCJpYXQiOjEzMzcsInBhc3N3b3JkIjoiaHVudGVyMiJ9.kcmTbx7M89k-3qUXN1UVcy9us6xdPZkDOqQ0UeY3Bws",
  "refresh_token": "RSzR4ngmJROKFJZQEpp5fNF4y",
  "authentication_method": "GoogleOAuth"
}
	

Putting it all together

	
(async () => {
  try {
    const requestData = await requestDeviceCode();
    promptUserToAuthenticate(requestData);

    const responseData = await pollForTokens(requestData.device_code, requestData.interval);
    console.log(chalk.green('\nAuthentication successful!'));
    console.log('Access Token:', responseData.access_token);
  } catch (err) {
    console.error(chalk.red('\nLogin failed:'), err.message);
  }
})();
	

That’s it! You’ve just added OAuth-powered login to your CLI. Your users can now authenticate securely through the browser, without ever pasting tokens by hand.

This site uses cookies to improve your experience. Please accept the use of cookies on this site. You can review our cookie policy here and our privacy policy here. If you choose to refuse, functionality of this site will be limited.