Illustration of a woman sitting at her computer while writing

# Creating a Tweet With NodeJS

This post is for day 1 of my #100DaysOfCode (opens new window). In this post I'll be discussing how to programmatically tweet to Twitter using NodeJS.

Portrait of Cody Bontecou Cody Bontecou  · Jul 16 2020 ·  minute read

# Getting Authenticated

Get a Twitter Developer Account (opens new window)

You'll need to follow the instructions of the link above to create a develop account. This gives you access to creating a project (opens new window) and an app (opens new window).

You'll eventually find yourself within the Twitter Developer Dashboard where you can generate authentication tokens that will be essential to making requests.

Screenshot of the Twitter Developer Dashboard

# Laying the Foundations of Your App

Github Repo (opens new window) to follow along

Make sure you have NodeJS (opens new window) installed

I prefer yarn (opens new window), but you can use npm instead if you prefer

  1. Scaffold your project: yarn init -y
  2. Download twitter-lite (opens new window) to interact with Twitter's API: yarn add twitter-lite
  3. Download dotenv (opens new window) to safely manage .env variables and your auth tokens: yarn add dotenv

Your package.json file should now look like this:

{
  "name": "programmatic-tweeting-with-nodejs",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "dot-env": "^0.0.1",
    "twitter-lite": "^1.1.0"
  }
}
  1. Create a .env file in your project root folder and add your tokens provided by Twitter's API

The .env file should look like this:

consumer_key = '<CONSUMER KEY>'
consumer_secret = '<CONSUMER SECRET>'
access_token_key = '<ACCESS TOKEN>'
access_token_secret = '<ACCESS TOKEN>'

Just make sure you replace the <> text with the tokens Twitter provided you.

Make sure you do not commit your .env file to Github or any other version control systems. These tokens are very important, and should not be shared with anyone!

# Making the Post

  1. Create an index.js file in your project root
  2. Import the packages you installed earlier
const twitter = require('twitter-lite')
require('dotenv').config()
  1. Create a client to talk to Twitter with your config
const client = new twitter(config)
  1. Code the request
client
  .post('statuses/update', { status: 'Hello World' })
  .then(result => {
    console.log('You successfully tweeted this : "' + result.text + '"')
  })
  .catch(console.error)

Step #4 is creating a POST request to Twitter's endpoint (opens new window) statuses/update with the parameter status = 'Hello World'.

  1. Make the request

Now type node index.js into your terminal and press enter. This will generate a Tweet with the text "Hello World".


I hope this article was helpful, let me know if you have any questions, comments, or suggestions on Twitter @codybontecou (opens new window)

Last Updated: 7/21/2021, 9:30:09 PM