Tweet using Node.js and Twitter API
Last Updated :
20 Jun, 2024
Tweeting programmatically using Node.js and the Twitter API can be a powerful tool for automating your social media interactions. Whether you’re looking to schedule tweets, respond to mentions, or analyze your Twitter data, Node.js offers a versatile platform for building Twitter bots and applications.
In this article, we will walk you through the steps to set up a Node.js environment, authenticate with the Twitter API, and send a tweet. We’ll use the twitter-api-v2
library, a modern and user-friendly wrapper around the Twitter API.
Approach
To create and post a tweet you can follow the steps below:
- Create a Twitter developer account & get API credentials (Link to create your developer account – https://developer.twitter.com/en )
- Create a new node project and initialize npm write the following commands in the shell.
Steps to Setup Project
Step 1: Make a folder structure for the project.
mkdir tweetPoster
Step 2: Navigate to the project directory
cd tweetPoster
Step 3: Initialize the NodeJs project inside the myapp folder.
npm init -y
Step 4: Install the necessary packages/libraries in your project using the following commands. Install twitter-api-v2 library using the following command in the shell.
npm install twitter-api-v2
Project Structure:

The updated dependencies in package.json file will look like:
"dependencies": {
"twitter-api-v2": "^1.17.1"
}
Step 5: Create an index.js file inside tweetPoster directory. Import twitter-api-v2 library in index.js
const { TwitterApi } = require("twitter-api-v2");
Step 6: Create a Twitter client by filling in your API keys and secrets, this will authenticate your account and allow you to use Twitter API to create requests and get responses.
const client = new TwitterApi({
appKey: "**",
appSecret: "**",
accessToken: "**",
accessSecret: "**",
bearerToken:"**",
});
Step 7: Provide read and write controls to your client so it can create new tweets
const rwClient = client.readWrite;
Step 8: ( For only text tweets) create a textTweet asynchronised function and then create a try-catch, inside the try block, create await tweet request using rwClient.v2, and inside .tweet() you can put any text in string format you want to tweet then put a console.log(“success”). So, in case of a tweet is posted successfully, success will get printed in the terminal. Now, add console.log(error) in the catch block. So, in case of any failure, error will get printed in the terminal.
const textTweet = async () => {
try {
await rwClient.v2.tweet(
"This tweet has been created using nodejs");
console.log("success");
} catch (error) {
console.error(error);
}
};
Step 9: (For text tweet with media) create a mediaTweet asynchronised function and then create a try-catch, inside the try block, create a mediaId const, and create await uploadMedia request (put the path of the image you want to post in place of “image_path”). The uploadMedia method is used to upload the media file, and the mediaId variable is assigned the unique identifier that Twitter assigns to the uploaded media. create await tweet request using rwClient.v2 and inside .tweet() you can put a JavaScript object.
{
text: "any text you wish to post with image/media ",
media: { media_ids: [mediaId] },
}
Step 10: Then put a console.log(“success”). So, in case of a tweet is posted successfully, success will get printed in the terminal. Now, add console.log(error) in the catch block. So, in case of any failure, error will get printed in the terminal.
const mediaTweet = async () => {
try {
const mediaId = await client.v1.uploadMedia("image_path");
await rwClient.v2.tweet({
text: "Twitter is a fantastic social network. Look at this:",
media: { media_ids: [mediaId] },
});
console.log("success");
} catch (e) {
console.error(e);
}
};
Step 11: Call any or both textTweet() & mediaTweet() methods.
textTweet();
mediaTweet();
Example: Implementation to Tweet using twitter API in nodeJS.
Node
// app.js
// Import twitter-api-v2
const { TwitterApi } = require("twitter-api-v2");
// Fill your API credentials
const client = new TwitterApi({
appKey: "**",
appSecret: "**",
accessToken: "**",
accessSecret: "**",
bearerToken: "**",
});
// Provide read write controls
const rwClient = client.readWrite;
// Create textTweet function which post
// a text only tweet
const tweetText = async () => {
try {
// Use .tweet() method and pass the
// text you want to post
await rwClient.v2.tweet(
"This tweet has been created using nodejs");
console.log("success");
} catch (error) {
console.log(error);
}
};
// Create tweet function which post
// tweet with media and text
const mediaTweet = async () => {
try {
// Create mediaID
const mediaId = await client.v1.uploadMedia(
// Put path of image you wish to post
"./1605232393098780672example.png"
);
// Use tweet() method and pass object with text
// in text feild and media items in media feild
await rwClient.v2.tweet({
text:
"Twitter is a fantastic social network. Look at this:",
media: { media_ids: [mediaId] },
});
console.log("success");
} catch (error) {
console.log(error);
}
};
// Call any of methods and you are done
textTweet();
mediaTweet();
Step to Run Application: Run the application using the following command from the root directory of the project
node index.js

output of the above program
Tweet Samples:

sample of only text tweet
Similar Reads
How to read and write JSON file using Node ?
Node JS is a free and versatile runtime environment that allows the execution of JavaScript code outside of web browsers. It finds extensive usage in creating APIs and microservices, catering to the needs of both small startups and large enterprises. JSON(JavaScript Object Notation) is a simple and
3 min read
Sending bulk SMS in Node.js using Twilio
SMS is a common method of sending short messages between cell phones, but these SMS can be sent to multiple users at a time using Twilio notify service. Sending bulk SMS to users at a time is possible using Twilio. Introduction: It's easy to get started and easy to use. It is widely used for sending
2 min read
How to display latest tweets from a twitter account using HTML ?
In this article, we will see how to display the tweets of any user on our web page using HTML. Twitter is one of the popular social media platforms. It is an American social networking service on which users can post and interact with messages called "tweets". only registered users can tweet, like,
2 min read
Real-time Notification System using Next.js and Socket.io
This article explains the process of creating a Real Time Notification System using Next.js and socket.io. In a typical scenario, imagine the need to create a user-friendly application. This application helps the user to send and receive notifications and can be used in multiple projects like E-comm
5 min read
Handling Requests And Responses in Node.js
Node.js is a powerful JavaScript runtime for building server-side applications. It provides an efficient way to handle HTTP requests and responses using the built-in http module or frameworks like Express.js. Understanding HTTP Requests and ResponsesAn HTTP request is sent by a client (browser or AP
4 min read
Extraction of Tweets using Tweepy
Introduction: Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and acce
5 min read
How to Create Sentiment Analysis Application using Node.js ?
Sentiment Analysis is a natural language processing technique used to determine emotions from textual data. It's often performed to know customer requirements, study product sentiment in user feedback, decision-making, and more. Types of Sentiment Analysis: Fine-grained Sentiment Analysis: It is don
10 min read
Sending SMS using NEXMO API in Node.js
Introduction: SMS is a common method of sending short messages between cell phones, but these SMS can be sent using API in Node.js. Now there are lots of API in the market for sending SMS like Twilio, Exotel, etc to the user but the popular among them is Nexmo. Features of NEXMO: Integrating this mo
2 min read
Travel Planning App API using Node & Express.js
In this article, weâll walk through the step-by-step process of creating a Travel Planning App With Node and ExpressJS. This application will provide users with the ability to plan their trips by searching for destinations, booking flights and hotels, submitting reviews, receiving notifications, sha
10 min read
How to Add Data in JSON File using Node.js ?
JSON stands for Javascript Object Notation. It is one of the easiest ways to exchange information between applications and is generally used by websites/APIs to communicate. For getting started with Node.js, refer this article. Prerequisites:NPM NodeApproachTo add data in JSON file using the node js
4 min read