DEV Community

Cover image for Twitter Followers Tracker using Next.js, NextAuth and TailwindCSS
Nilanth
Nilanth

Posted on • Updated on • Originally published at javascript.plainenglish.io

Twitter Followers Tracker using Next.js, NextAuth and TailwindCSS

Steps to build Twitter followers counter using Next.js, NextAuth, SWR, Tailwind CSS with Dark Mode Support.

To learn new things, just reading the docs is not enough. We should practically apply it. Likewise, while learning new tech stacks we should apply them by developing simple apps to get a hands-on experience. 

So to learn some new tech stacks let build a small application. Here we are going to learn Next.js, NextAuth, SWR and Tailwind CSS by developing a Twitter followers counter app. 

We are going to build an app like TwiterStats.

Tech Stack

  1. Next.js for building ReactJS Application.
  2. NextAuth for OAuth implementation with Twitter.
  3. SWR for fetching data from API.
  4. Tailwind for UI
  5. Twitter Lite for fetching data from Twitter APIs.

Next.js and Tailwind Setup

We can setup tailwind with next.js using a single command, as shown below:

npx create-next-app -e with-tailwindcss twitter-count
Enter fullscreen mode Exit fullscreen mode

The above command automatically configures the Tailwind setup based on the official Next.js example.

Once the installation is completed navigate to your project folder using cd twitter-count and start the dev server using yarn dev command. You can see the below page if you hit http://localhost:3000 in the browser.

next-home

Configure NextAuth.js

What is NextAuth?

NextAuth is an open-source Authentication package for Next.js. NextAuth simplifies the social auth logins like Twitter, Google, Apple, Github and many more. It also supports email or passwordless login and database integration.

Add next auth to your project using the below command

yarn add next-auth
Enter fullscreen mode Exit fullscreen mode

Next, create a file named […nextauth].js in pages/api/auth folder and add the below code

Let's break down the above code

Above NextAuth function handles the dynamic route for all social auth. Here we are going to use Twitter OAuth, so we have added TwitterProvider in providers. To perform successful OAuth we require TWITTER_ID and TWITTER_SECRET, Get these from the Twitter Developer Platform with a few simple steps. 

Follow the steps in this link to get Twitter API access.

After getting the Secrets from the developer portal, Update it in the env and add to the provider as above. 

Using callback set the required data in session after successful OAuth with Twitter. On Successful OAuth, we get many details from Twitter, Here we will customize the data that we require and save it in session. 

We should not expose secrets such as authToken and authSecret to the client-side, so we save them in JWT token objects. Then we can access the user credential on the server-side using the getToken helper method.

secret a random string used to hash tokens, sign or encrypt cookies and generate cryptographic keys.

Configure SessionProvider

Warp the SessionProvier context at the top-level component to use useSession hooks to get session data in child components as below

refetchInterval is used to fetch the session periodically in the background.

In our app, _app.js is the top-level component, so we have wrapped the session provider. Here we have wrapped ThemeProvide context from next-theme to enable dark mode support. 

Followers Counter Component

Add the below code in Followers Components

Break Down the Followers Component

What is SWR?

SWR is a React Hooks for Data Fetching developed by the Next.js team. It supports real-time data fetching, built-in cache, Auto Revalidation, Prefetching and more.

In the followers component, we have called /api/twitter/user API to get basic details of the Twitter user such as name, followers count, profile description and location. We have used SWR to get the data from the API in an interval of time.
 
As the data we get from NextOAuth is not real-time data. So we use Twitter Lite API to get the Twitter user details in real-time. 

Twitter Lite Integration

Twitter Lite is a tiny, full-featured, flexible server library for Twitter APIs.

In Next.js you can build APIs also, files inside api/* are considered as API endpoints. Which are processed on the server, not on the client-side. Twitter APIs can be accessed from the server-side only, so we have a user API in the api/ folder to access the show API using the Twitter lite package.

Add the below code pages/api/twitter/user.js to access the user details using /api/twitter/userAPI.

Add the Followers component in index.js file as below.

Here we use signIn and signOut the method from next-auth to initiate OAuth login. To log in with Twitter we pass Twitter param to the sign-in method as below

signIn('twitter');
Enter fullscreen mode Exit fullscreen mode

Now just hit the URL in the browser to see the changes like below

login

On calling the signIn method, the app will be redirected to the Twitter OAuth page and clicking the Authorize App button on OAuth Page will redirect back to our followers component as below image.

follower-image

We need to configure the OAuth redirect URL in Twitter Developer Portal when registering.

You can customize the UI based on your need, Here I have covered only the integration part and with basic UI using tailwind.

Deploying in Vercel

You can deploy your Counter App in Vercel within two steps as below:

  1. Create a Vercel Account
  2. Connect your repository and click deploy.

Links

GitHub Repo -> https://github.com/Nilanth/twiter-stats

Live Demo -> https://twiter-stats.vercel.app

Conclusion

We have successfully integrated Twitter with NextAuth and displayed the follower's count using Next and tailwind. We have got hands-on experience with these tech stacks now.

Thank you for reading

Get more updates on Twitter.

eBook

Debugging ReactJS Issues with ChatGPT: 50 Essential Tips and Examples

ReactJS Optimization Techniques and Development Resources

More Blogs

  1. Don't Optimize Your React App, Use Preact Instead
  2. How to Reduce React App Loading Time By 70%
  3. Build a Portfolio Using Next.js, Tailwind, and Vercel with Dark Mode Support
  4. No More ../../../ Import in React
  5. 10 React Packages with 1K UI Components
  6. 5 Packages to Optimize and Speed Up Your React App During Development
  7. How To Use Axios in an Optimized and Scalable Way With React
  8. 15 Custom Hooks to Make your React Component Lightweight
  9. 10 Ways to Host Your React App For Free
  10. How to Secure JWT in a Single-Page Application

Latest comments (3)

Collapse
 
get_your_slice profile image
Slice🍕

Hello,
I used you code. Thank you so much. I have one problem. When I logout and login again, it keeps asking me to click on Authorise app button on Authorisation page. Do you know why? I am using v2.

Collapse
 
dhravya profile image
Dhravya

Hey Nilanth!
Is this using twitter API v2, or V1

Collapse
 
jacklynch00 profile image
Jack Lynch

This is currently using v1.1. In order to use v2, you need to enable that in the NextAuth config like so:

providers: [
        TwitterProvider({
            clientId: process.env.TWITTER_ID,
            clientSecret: process.env.TWITTER_SECRET
            version: "2",
        }),
    ],
Enter fullscreen mode Exit fullscreen mode