Posting to Twitter via Node.js

— 3 minute read

permalink

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 permalink

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 by creating a new app; We don't need anything special for this app.

Connecting to the Twitter API with Node.js permalink

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

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:

var Twitter = require('twitter');

var 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 our 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 as well as the raw response to see what we actually 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! permalink

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 see addressed.