DEV Community

Nick Bull
Nick Bull

Posted on

Deploying Twitter Post Scheduler Built With React, NodeJS, FaunaDB and Vercel (Part 2)

Introduction

In our first article, we have created a Twitter post scheduler called Twittler with React, Node.js, and Fauna. In this chapter, we will deploy it to the Vercel.

Why Vercel?

Vercel is the best place to deploy any frontend app with zero configuration and scale it dynamically to millions of pages without breaking a sweat. As an addition, we can deploy our backend as serverless functions without any additional configuration. Serverless functions are pieces of code written with backend languages that take an HTTP request and provide a response.

Tools

Before we start, make sure you have:

  1. A Vercel account where we will deploy our application. You can create it here.
  2. A Github account as our version control. You can create it here.
  3. A Cronhub account where our cron job will be located. You can create it here.

Deployment Architecture

Here is how Twittler high-level deployment architecture will look like:

fauna twittler

  1. We push our app to Github using the git --push command.
  2. Then Github pushes our code to Vercel automatically.
  3. Vercel builds it and makes it live.

To create this architecture and bring it to life, we need to:

  1. Create a Github repository for our application.
  2. Make small changes in our codebase to make it suitable with Vercel serverless functions.
  3. Connect our Github repository with Vercel, to automate Github → Vercel deployment.

Let’s start!

Pushing Twittler to Github

To push our application to Github, first, we need to create a Github repository. It’s a place that will contain all of our project's files and each file's revision history. To create a repository follow these steps:

  1. Go to the “Create a new repository” page.

    fauna twittler

  2. Add repository name (I used “twittler”)

  3. Click on the “Create repository” button.

We’ve created a repository! Now, let’s push our existing codebase to it. To do it, follow these steps:

  1. Using your terminal/command line, get inside the folder where your project files are kept: cd your_path_to_the_application and press enter.
  2. Type git remote add origin [git@github.com](mailto:git@github.com):YOUR_GITHUB_USERNAME/REPO_NAME.git and press enter.
  3. Type git branch -M main and press enter.
  4. Type git add . and press enter.
  5. Type git commit -m "first commit" and press enter.
  6. And finally, type git push -u origin main and press enter. It will push our application to Github.

If you are having difficulties with pushing your application, use this guide or official Github recommendations:

fauna twittler

To make sure your application is on Github, go to https://github.com/YOUR_GITHUB_NAME/twittler and check if you see your local files there.

Making our Application Suitable for Vercel

Vercel doesn’t support cron jobs at the moment so we will use Cronhub to handle our Twitter posting job, which is located in the server/index.js file.

With Cronhub, we can create a recurring task that will call our Vercel serverless function every minute and post tweets on Twitter. Basically, we will create an API route that the cron job will call every minute.

This is how our application architecture will change due to that.

From:

fauna twittler

To:

fauna twittler

Let’s start with transforming our server/indiex.js.

From Express.js to Vercel Serverless Functions

To create and deploy serverless functions without additional configuration, we need to place a file with our Twitter posting functionality, wrapped in an exportable function, in the /api directory at the root of our project. To do it, follow these steps:

  1. Go to the root folder of Twittler project.
  2. Create an api folder.
  3. Put there cron.js file (you can use any name here).
  4. And add to it this code.

    const faunadb = require('faunadb')
    const {TwitterApi} = require('twitter-api-v2')
    const twitterClient = new TwitterApi(process.env.TWITTER_BEARER_TOKEN)
    
    const q = faunadb.query
    const faunaClient = new faunadb.Client({
      secret: process.env.REACT_APP_FAUNADB_SECRET,
    })
    
    module.exports = async (req, res) => {
      if (req.method === 'POST') {
        try {
          const now = new Date()
          now.setSeconds(0)
          now.setMilliseconds(0)
    
          // get all tweets from Now - 1 minute to Now
          const {data} = await faunaClient.query(
    
            q.Map(
              q.Paginate(q.Match(q.Index('tweetsByDate'), now.getTime())),
              q.Lambda(['date', 'ref'], q.Get(q.Var('ref')))
            )
          )
    
          // post all tweets from date range on twitter
          data.forEach(async ({data: {tweet}}) => {
              await twitterClient.v1.tweet(tweet)
          })
    
          res.status(200).json({success: true})
        } catch (err) {
          res.status(500).json({statusCode: 500, message: err.message})
        }
      } else {
        res.setHeader('Allow', 'POST')
        res.status(405).end('Method Not Allowed')
      }
    }
    
    

Creating a cron.js file in the /api directory will provide us with an API call https://ourapp.com/api/cron that will post tweets on Twitter.

Deploying to Vercel

Before we deploy our application on Vercel let’s push our latest changes to the Github repository. Open terminal, go to the root folder of your project and run:


git add .

git commit -m “vercel setup”

git push -u origin main

Enter fullscreen mode Exit fullscreen mode

Now, let’s deploy our application to Vercel:

  1. Go to the new Vercel project page.
  2. Choose your repository and click the “Import” button.

    Alt Text

  3. Configure your project by adding project name and all environment variables from your .env.local file in the project root folder to Environment Variables tab like this:

    Alt Text

  4. Click on the “Deploy” button.

Great, our application is live!

The last thing we have to do is create a cron job that will call it every minute.

Moving Cron Job to Cronhub

To move our cron job to Cronhub follow these steps:

  1. Go to “Scheduler” tab and click on “+ New Scheduler” button

    Alt Text

  2. Create your cron job:

    Alt Text

    You can find your “Target HTTP URL” at your Vercel domain settings:

    Alt Text

  3. Click on the “Save” button.

We have created our cron job!

You can verify it by going to “Shedulers” tab:

Alt Text

What this job does is make a POST request to yourdomain.com/api/cron every minute. The handler function, located on the yourdomain.com/api/cron, fetches all tweets from Fauna and publishes them to Twitter.

Conclusion

Congratulations! We created and deployed the Twitter scheduler application.

You can find a repository with the final example here.

Written in connection with the Write with Fauna Program.

Discussion (0)