How to start TwitterOAuth with Express.js
Tags: node, javascript, beginners, express
Published: 2021-11-02 12:57:23

What kind of procedure OAuth process in Twitter?
If you want tweet with OAuth flow,You must get Access token and access token secret.

## twitterOAuth flow

### Preparation
Getting oauth_consumer_key,oauth_consumer_secret, and setting oauth_callback in Twitter Developers.

![display key and tokens](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lmmpi7kj19adf1z3r9hx.png)
 

![setting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/do3p1gj855j4ulfb5hg3.png)
 

- oauth_consumer_key(=API Key)
- oauth_consumer_secret(=API Key Secret)
- oauth_callback:without this URL,error in OAuth flow.

### 1. POST to oauth/request_token
After POST to oauth/request_token with oauth_consumer_key and oauth_callback,you'll get this.
- oauth_token(=request token)
- oauth_token_secret(=request token secret)
- oauth_callback_confirmed.

### 2. GET to oauth/authorize
redirect to your setting callback_url containing the oauth_token and oauth_verifier.

### 3. POST oauth/access_token

post to oauth/access_token includes oauth_consumer_key,oauth_token(=request token),and oauth_verifier.
So,you can receive oauth_token(=access token) and oauth_token_secret(=access token secret).

After saved this,use twitter client library.

```js
fucntion twitterPost(consumerKey,consumerSecret,AccessTokenKey,AccessTokenSecret){
  const Twitter = require('twitter');
  const client = new Twitter({
    consumer_key: consumerKey,
    consumer_secret: consumerSecret,
    access_token_key: AccessTokenKey,
    access_token_secret: AccessTokenSecret
  });
}
```

## TwitterOAuth with express
using this
- express
- express-session
- node-twitter-api

### Preparation
loading environment variables from a .env file

```js
const consumerKey = process.env.CONSUMER_KEY;
const consumerSecret = process.env.CONSUMER_SECRET;
const callbackURL = process.env.CALLBACK_URL;
```

setting session.

```js
app.use(
  session({
    secret: "keyboard cat",
    resave: true,
    saveUninitialized: false,

    cookie: { secure: false,},
    key: "sid",
  })
);
```
Saving to session oauth_token(=requestToken) and oauth_token_secret(=requestTokenSecret).
GET oauth/authenticate after that.
```js
const twitterAPI = require("node-twitter-api");

const twitterapi = new twitterAPI({
  consumerKey: consumerKey,
  consumerSecret: consumerSecret,
  callback: callbackURL,
});

router.get("/", (req, res) => {
  const sess = req.session;
  twitter.getRequestToken(function (
    error,
    requestToken,
    requestTokenSecret,
  ) {
    if (error) {
      console.log("Error getting OAuth request token : " + error);
    } else {
      sess.requestToken = requestToken;

      sess.requestTokenSecret = requestTokenSecret;
      res.redirect(
        `https://twitter.com/oauth/authenticate?oauth_token=${requestToken}`
      );
    }
  });
});
``` 
after verify your app,redirect your setting callback_url.check request_token.
![verify](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9nmh7gfsbdokiy3piuym.png)

```js
router.get("/callback", (req, res) => {
  const sess = req.session;
  const requestTokenSecret = sess.requestTokenSecret;
  const oauth_token = req.query.oauth_token;
  const oauth_verifier = req.query.oauth_verifier;

  twitter.getAccessToken(
    oauth_token,
    requestTokenSecret,
    oauth_verifier,
    function (error, accessToken, accessTokenSecret) {
      if (error) {
        console.log("access token error!");
        console.log(error);
      } else {
        sess.token = accessToken;
        sess.tokenSecret = accessTokenSecret;
        res.redirect("/twitterPost");
      }
    }
  );
});

app.get("/twitterPost", (req, res) => {
  const sess = req.session;
  twitterPost(
    consumerKey,
    consumerSecret,
    sess.token,
    sess.tokenSecret,
  );
  res.send(
    `your tweet was posted!`
  );
});
```