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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay