DEV Community

Vansh Wadhwa
Vansh Wadhwa

Posted on

Twitter Pin Based OAuth in NodeJS / Typescript

This is how you can use twitter pin based oauth in node.js / typescript.

Steps:

Step 1
Install @vanxh/tw-oauth in your project

npm install @vanxh/tw-oauth
# or
yarn add @vanxh/tw-oauth
Enter fullscreen mode Exit fullscreen mode

Step 2
Import TWoauth

import { TwoAuth } from 'twoauth';
Enter fullscreen mode Exit fullscreen mode

Step 3
Create a new TWoauth instance

const tw = new TwoAuth("API KEY", "API SECRET");
Enter fullscreen mode Exit fullscreen mode

Step 4
Get an authorization URL

const { token, tokenSecret, authorizationUrl } = await tw.getAuthorizationUrl();
console.log(authorizationUrl);
Enter fullscreen mode Exit fullscreen mode

Step 5
Use the pin you get after authentication on the authorization URL in Step 4 to get the access token and access token secret.

const { accessToken, accessTokenSecret } = await tw.getAccessToken(pin, token, tokenSecret);
Enter fullscreen mode Exit fullscreen mode

Full Usage Example

Check out the library on github.

import { TwoAuth } from 'twoauth';
import inquirer from "inquirer";
import open from "open";

const tw = new TwoAuth("API KEY", "API SECRET");

const { token, tokenSecret, authorizationUrl } = await tw.getAuthorizationUrl();
console.log("Please visit the following URL to authorize the app.");
console.log(authorizationUrl);
open(authorizationUrl);

const { pin } = await inquirer.prompt([{
  type: "number",
  name: "pin",
  message: "Paste the PIN here:",
  filter: (value) => (value >= 0 && value <= 9_999_999) ? value : Promise.reject(`Invalid PIN: ${value}`)
}]);

const { accessToken, accessTokenSecret } = await tw.getAccessToken(pin, token, tokenSecret);
console.log("Access Token:", accessToken);
console.log("Access Token Secret:", accessTokenSecret);

// Use the access token and access token secret to make API calls to Twitter API.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)