DEV Community

Vansh Wadhwa
Vansh Wadhwa

Posted on

1 1 1 1 1

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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Image of Docusign

πŸ› οΈ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more