Simplified GitHub Authentication in Next.js with next-auth: A Step-by-Step Tutorial

Simplified GitHub Authentication in Next.js with next-auth: A Step-by-Step Tutorial

·

9 min read

In this article, you will learn how to leverage next-auth to enhance user authentication by signing in with your GitHub profile.

Requirements

  • Make sure you should have a GitHub account. If you do not have one, click here to create one.

  • Ensure you have Nodejs installed on your machine.

  • A Basic Knowledge of React/nextjs and typescript is needed

Introduction to NextJs

What is NextJs?

Nextjs also known as Next is a React framework used to build fullstack web applications. It uses a rust compiler popular known as SWC that helps in faster builds.

Why is NextJS important?

  • Built-in Optimizations: Nextjs offer Built-in Optimizations to enhance the user experience in web applications.

  • Data-Fetching: With NextJs, you can make your components asynchronous and await your data.

  • Client and server-side rendering: This is a great feature that Next offers. With Next, your rendering can also be handled by the server.

NextJs Installation

System Requirements:

  • Node.js 16.14 or later.

    Ensure you are on the terminal before following these steps:

    Type this command in your terminal to start a new nextjs app.

npx create-next-app@latest

On installation, you will see the following prompts:

What is your project named? my-app 
Would you like to use TypeScript? No / Yes  -> yes
Would you like to use ESLint? No / Yes      -> No(not needed)
Would you like to use Tailwind CSS? No / Yes  -> -> yes
Would you like to use `src/` directory? No / Yes   -> yes
Would you like to use App Router? (recommended) No / Yes  -> yes
Would you like to customize the default import alias? No / Yes -> no (not needed) 
What import alias would you like configured? @/* No / Yes  -> no (not needed)

Make sure you give a suitable title and enable typescript, tailwindcss and App Router for this project.

After the prompts, create-next-app will create a folder with your project name and install the required dependencies.

Installing next-auth

After setting up your Next App, you also need to install next-auth with your nextjs project to provide authentication.

Installation:

  • Type this command to install next-auth
npm install next-auth

Cleanup of the App

  • Inside your app directory, go to the app/page.tsx directory, inside the page.tsx file do a cleanup and copy the following code snippet.
import Image from 'next/image'

export default function Home() {
  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">

    </main>
  )
}
  • Next, go to the app/layout.tsx directory, Inside the layout.tsx file, make sure you do a cleanup and copy the code snippet.
import './globals.css'
import type { Metadata } from 'next' // import the type for your app metadata
import { Inter } from 'next/font/google' // import the font for your next app
import Provider from '../../provider/provider' // import the Provider used to wrap your app 

const inter = Inter({ subsets: ['latin'] })

export const metadata: Metadata = { // here you define the metadata for your App 
  title: 'Github Authentication with next',
  description: 'Understanding how to setup github authentication',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body className={inter.className}>
       <Provider>
         {children}
        </Provider>
    </body>
    </html>
  )
}

Lastly, In your app/globals.css directory ensure you remove some of the default styles on the file and leave it like this:

/*global.css file */

@tailwind base;
@tailwind components;
@tailwind utilities;

Setting up a GitHub OAuth Application

If you are looking to integrate GitHub into your application, it is required to setup a GitHub oauth application.

While setting up a Github oath application, you will be given a client id and a client secret to integrate GitHub into your nextjs application. In this section, you will learn how to get your GitHub client id and client secret from your account.

  • Log in with your GitHub account

  • Click on your profile and go to settings

  • Scroll down and click on developer settings

  • Next, go to the OAuth Apps tab, and make sure you click on the New OAuth App button as shown below.

  • Make sure you give your OAuth application a suitable name, Homepage URL (the url your app is hosted at the moment) which is localhost:3000 and lastly, the Authorization callback URL which is the url the user is redirected to after a successful authorization. Then, click on register application to complete the process

After creating your OAuth application, you will be given your client id and client secrets for your GitHub integration.

Ensure you copy them and put them on a notepad for future purposes

Creating an .env file

In the previous section, you have covered how to setup a GitHub oauth application. In this section, you will create an env file that stores key-value pairs that determine your app behavior.

What is a .env file

It is a simple text configuration file for controlling your Application environment constants.

Create a .env file in your root directory using the command below:

touch .env

Ensure you are in the right directory before running the command above

Inside the .env file you just created, add the following keys

GITHUB_CLIENT_ID = <YOUR_GITHUB_CLIENT_ID>
GITHUB_CLIENT_SECRET = <YOUR_GITHUB_CLIENT_SECRET>

Replace <GITHUB_CLIENT_ID> with your github client id and GITHUB_CLIENT_SECRET with your GitHub client secret key which was generated when setting the GitHub oauth application.

Adding the Api Route:

To integrate next-auth into your project, it is necessary to create an API route because it provides a structured and secure way to manage authentication-related logic on the server side.

  1. Go inside the src/app directory and create a directory named api/auth/[...nextauth].

  2. Inside the api/auth/[...nextauth] directory, create a route.ts file.

  3. Inside the route.ts file, add the following code snippet.

import type {NextAuthOptions} from "next-auth"
import GithubProvider from "next-auth/providers/github" //import the GithubProvider module
import NextAuth from "next-auth/next" //import the NextAuth module


 const handler: NextAuthOptions = NextAuth({
    providers:[
        GithubProvider({
            clientId: process.env.GITHUB_CLIENT_ID as string, //passing in your github client_id as the value
            clientSecret: process.env.GITHUB_CLIENT_SECRET as string //passing in your github_client_secret as the value
        }),
    ],   
})

export {handler as GET, handler as POST}

In the code snippet above:

  1. The NextAuthOptions type is imported from the next-auth library to define the type for the handler

  2. GithubProvider is imported from the GitHub provider's library in next-auth

  3. The NextAuth module makes it easy for you to configure your authentication provider.

  4. A handler object is created and defined with the type NextAuthOptions and inside the handler object, a providers array is created and provided with the GithubProvider function that is called and then passed an object option as the parameter

  5. The handler object is exported as a GET and POST request.

Creating the Session Provider

If you are looking to access the data of the user that gets signed into the frontend application, you need the sessionProvider.

The session Provider is the custom context provider that makes data globally available to the application. In your root directory, create a folder named Provider. Inside the provider folder, create a file named provider.tsx and copy the following code snippet

"use client"
import React from "react";
import { SessionProvider } from "next-auth/react";

interface SessionProviderProps {
    children: React.ReactNode
}


const Provider = ({children}: SessionProviderProps) => {
  return <SessionProvider>
    {children}
  </SessionProvider>
}

export default Provider

Creating the GitHub Button for Sign-In

Go to your app directory and create a component folder. Inside the component folder, create a signin.tsx file which is the UI component that has the GitHub button for signin. Next, copy the following code snippet inside the signin.tsx file.

"use client"

import React from 'react'
import { signIn, signOut } from 'next-auth/react'
import { useSession } from 'next-auth/react'
import { useRouter } from 'next/navigation'


const Signin = () => {
  const {data: session} = useSession()
  const router = useRouter()

  if(session) {   //when there is session, the user gets signed in with the session
   router.push("/User")
  }



  return (
    <div className='flex flex-col justify-center items-center gap-[12px]'>
      <p>
        Simplified GitHub Authentication
      </p>

      <div>
       <button className='bg-[#000] text-[#fff] px-3 py-3 rounded-md' onClick={() => signIn()}>
       Login 
       </button>  
      </div>

    </div>
  )
}

export default Signin

In this code snippet above:

  1. "use client" text is written at the top since client-side functionality is been used in the component.

  2. After calling the useSession function, the data that is globally available throughout the application is being accessed.

  3. An instance is created after the useRouter hook is called representing the router that helps in navigating to the User page when there is a session.

  4. Inside the layout, the button is passed in the signIn function that helps you to sign in with your GitHub account.

After creating the Signin component, go to your app/page.tsx directory and update the page.tsx file with the following code snippet

import Image from 'next/image'
import Signin from './component/signin' //import the signin component

export default function Home() {
  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
     <Signin/>
    </main>
  )
}

Creating the User Component

This is the component that a user is redirected to when signed in successfully with a GitHub account...Inside your app directory, create a directory(folder) named User and inside the directory, create a page.tsx file and copy the following code snippet. So in nextjs, pages are created when you add a javascript file to a specific directory

Routing in nextjs is based on a file-based routing system

"use client"

import React, { useEffect } from 'react'
import { useSession } from 'next-auth/react'
import { signIn, signOut } from 'next-auth/react'
import { useRouter } from 'next/navigation'

const user = () => {
  const { data:session } = useSession()
 console.log(session)
 const router = useRouter()


  useEffect(() => {
    if(!session) {
      router.push("/")
    }
  },[session])

  if(!session) { // if there is no session, show the loading text
    return (
      <div className='text-center'>
        Loading...
      </div>
    )
  }

  return (
    <>
    <div className='flex flex-col justify-center items-center'>
      <p className='mt-4'>
        You are welcome {' '}
       <span className='font-bold'>{session?.user?.name}</span> 
      </p>
      <p className='my-4'>
        Here is your email {" "}
      <span className='font-bold'>{session?.user?.email}</span>
      </p>


      </div>
      <div className='flex justify-center'>
        <button onClick={() => signOut()} className='bg-red-500 rounded-md px-3 py-3'>
          Sign out
        </button>
       </div>
    </>

  )
}

export default user

Inside the code above:

  1. Since all components are server components by default in nextjs, the "use client" is used as a directive in nextjs to turn a component into a client component.

  2. The useSession hook is called to access the data that is gotten when you sign in successfully with your GitHub account.

  3. Now in the layout, Your GitHub name and email property are rendered from the session object.

  4. Then the button is passed the signOut function that allows a user to sign out from the authenticated session.

Trying the Application

Hurray🥳 , You have just built a nextjs app with seamless GitHub authentication.

Conclusion

This tutorial taught you how to build a simple application with seamless Github authentication using Nextjs, Next-auth library and Github...

Contact me at if you have any questions. thank you