Subscribe

Posting to Twitter via Node.js

โœ๏ธ

Tweeting via the Twitter API using Node.js VanillaJs

25 Mar, 2020 ยท 2 min read

So this week, we have been working on our RSS social posting app, as mentioned in yesterday's article we are looking into posting with Twitter's API via Node.js

Read more: Basic Node.js Express application

Posting to Twitter

Same as Facebook yesterday, Twitter also has quite a signup process to become a developer.

Visit: Twitter developer and sign up for an account (this can take a while!)

Once you have your developer account, we can start creating a new app; We don't need anything special.

Connecting to the Twitter API with Node.js

So with Twitter, we will skip the part of doing a graph-like test (you could use postman if you want to).

For the node.js part, we are going to add the following Twitter package make sure you open the correct folder in the terminal, then run the following command:

npm i twitter

Then we open our index.js page and add the following script:

const Twitter = require('twitter');

const client = new Twitter({
  consumer_key: '{CONSUMER_KEY}',
  consumer_secret: '{CONSUMER_SECRET}',
  access_token_key: '{ACCESS_TOKEN_KEY}',
  access_token_secret: '{ACCESS_TOKEN_SECRET}',
});

client.post(
  'statuses/update',
  { status: 'Posting via the API is awesome!' },
  function (error, tweet, response) {
    if (error) throw error;
    console.log(tweet); // Tweet body.
    console.log(response); // Raw response object.
  }
);

First, we define our Twitter package import. Next, we define a new Twitter client and add the four parameters we got from the Twitter app we just created.

Then we do an actual post to the statuses/update endpoint and pass a status object (your tweet) to it.

Next, in the response, we log both the tweet and the raw response to see what we get!

That's all we can now run the following command to test out our node.js posting to Twitter.

node index.js

Let's tweet and connect!

You can find today's code here on GitHub.

So now, you figured out how to post to Facebook and Twitter via node.js. Let me know how this went for you and what topics you still want to address.

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

Posting with the Facebook API via Node.js

24 Mar, 2020 ยท 2 min read

Posting with the Facebook API via Node.js

NVM set default version

20 Jul, 2022 ยท 2 min read

NVM set default version

Join 1829 devs and subscribe to my newsletter