Send a tweet with Node.js

This script uses the twitter-api-v2 npm module to send tweets using the Twitter API.

Project setup

This assumes you're working in a Node.js project. If you don't have one, create an empty folder folder and run npm init -y. Then install these two dependencies:

npm install twitter-api-v2 npm install --save-dev dotenv

Setup Twitter credentials

You'll need to create a Twitter account if you don't have one already.

Then go to the Twitter API and create a new App with Read and Write access under 'User authentication settings' (more info on that here).

There are 4 credentials you need to save in order to send tweets via the API. The API key and secret are shown when you create the app - store those in a safe location. Those give you basic access to the API.

Then to get the access token and secret for sending tweets: within the App settings, under the Keys and tokens tab, under Authentication Tokens click 'Generate' and save the access token & secret.

Then create a .env file with the app's key and secret, and the access token and secret:


The sendTweet function

Now you're good to go. Then put this in a file, eg tweet.ts:

require('dotenv').config(); import { TwitterApi } from 'twitter-api-v2'; const twitterUserConfig = { appKey: process.env.TWITTER_API_KEY ?? '', appSecret: process.env.TWITTER_API_SECRET ?? '', accessToken: process.env.TWITTER_ACCESS_TOKEN, accessSecret: process.env.TWITTER_ACCESS_SECRET, }; const userClient = new TwitterApi(twitterUserConfig); export const sendTweet = async (text: string) => { try { await userClient.v1.tweet(text); return true; } catch (err) { console.log('Error sending tweet:', err); } return false; };

And that's all you need to send automated tweets! You'd call this function in another file like this:

import { sendTweet } from './twitter'; (async () => { await sendTweet("I no longer have a manager. I can't be managed"); })();