Cody Bontecou

Post to Reddit using its API

July 18, 2020 · 3 minute read · nodejs,typescript,reddit

This post is for day 2 of my #100DaysOfCode. In this post I'll be discussing how to programmatically post to Reddit using NodeJS and Typescript.

Getting Authenticated

Getting an authentication token for Reddit is complicated.

If you have a business and plan on this token generating income, follow this form.

For personal use, navigate to your Reddit apps and scroll to the bottom of the page. You should see a grey button that says "create another app...". Click the button and fill out the form. Successfully submitting this form should generate

Reddit developer application information. Includes your client ID and client Secret needed for API calls

Laying the Foundations of Your App

Github Repo to follow along

Make sure you have NodeJS installed

I prefer yarn, but you can use npm instead if you prefer

Copy this package.json file and run yarn install to install the dependencies.

{
  "name": "reddit-post",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "dev": "ts-node index.ts"
  },
  "devDependencies": {
    "ts-node": "^10.1.0",
    "typescript": "^4.3.5"
  },
  "dependencies": {
    "dotenv": "^10.0.0",
    "snoowrap": "^1.23.0"
  }
}

Packages explained:

  • ts-node is a handy tool for executing Typescript files without having to first compile to Javascript.
  • Typescript superset of Javascript. I'm simply using it to try to become more comfortable with it in day-to-day projects.
  • dotenv to safely manage .env variables and your auth tokens.
  • snoowrap provides a simple interface to access every reddit API endpoint.

Create a .env file

.env files are used as a best practice to keep secret keys (such as our authentication tokens) off of GitHub. Make sure to have a .gitignore file and add .env to it.

The .env file should look like this:

username = '<REDDIT USERNAME>'
password = '<REDDIT PASSWORD>'
clientId = 'CLIENT_ID'
clientSecret = 'CLIENT SECRET'

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!

Performing the POST request

  1. Create an index.ts file in your project root
  2. Import the packages you installed earlier
const snoowrap = require('snoowrap')
require('dotenv').config()
  1. Create config object to organize your Reddit configuration variables
const config = {
  username: process.env.username,
  password: process.env.password,
  clientId: process.env.clientId,
  clientSecret: process.env.clientSecret,
}
  1. Create a function that sends out a POST request to Reddit's endpoint /api/submit with the title, link, and subreddit parameters.
function postLink(title: string, link: string, subreddit: string) {
  const r = new snoowrap({
    userAgent: 'Whatever',
    clientId: config.clientId,
    clientSecret: config.clientSecret,
    username: config.username,
    password: config.password,
  })
  r.getSubreddit(subreddit).submitLink({
    title: title,
    url: link,
    sendReplies: true,
  })
}

Explained:

const r = new snoowrap({
  userAgent: 'Whatever',
  clientId: config.clientId,
  clientSecret: config.clientSecret,
  username: config.username,
  password: config.password,
})

This snippet of code is creating a new snoowrap instance that connects to the Reddit service.

r.getSubreddit(subreddit).submitLink({
  title: title,
  url: link,
  sendReplies: true,
})

getSubreddit: Generates a Subreddit object. You can read more about this object here.

submitLink: Creates a new link submission on this subreddit with the title provided, url of the link, and any other options that the snoowrap api allows, such as the sendReplies option that allows replies to the post to send replies to the authenticated user's inbox.

  1. Make the request

Now add

postLink(
  'Post to Reddit with NodeJS and Typescript',
  'https://codybontecou.com/post-to-reddit-with-nodejs-and-typescript.html',
  'webdev'
)

with the parameters you want to use at the bottom of index.ts.

Once you are ready, type yarn dev into your projects terminal. If all is good, you should be able to see your post is now on Reddit!

Bonus

Make this more dynamic by iterating over multiple subreddits within an array:

const url =
  'https://codybontecou.com/post-to-reddit-with-nodejs-and-typescript.html'
const title = 'Post to Reddit using its API'
const subreddits = ['webdev', 'learnjavascript', 'typescript', 'programming']

subreddits.forEach(subreddit => postLink(title, url, subreddit))

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

Newsletter

Subscribe to get my latest content. No spam.