NextAuth.js authentication with Github and Google in NextJs

haroldmud

Harold Mudosa

Posted on November 29, 2024

NextAuth.js authentication with Github and Google in NextJs

NextAuth aims to make authentication simple, yet secure in Next.js apps. it handles automatically practices like passwordless flow, scoping access and more.

With it you can simply get authenticated through your existing logins from different platforms like Google, Atlassian, github, etc.

schema

Step by step guide

Step 1. Setting up NextAuth for sign in

  • Run npm install next-auth@4.24.7 to install next auth dependecies
  • In in your src/app directory create a lib directory in which you'll add the authOptions.ts file with the following changes:
//src/app/lib/authOptions.ts

import { NextAuthOptions } from "next-auth";
import GithubProvider from "next-auth/providers/github";
import GoogleProvider from "next-auth/providers/google";

export const authOptions: NextAuthOptions = {
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET
    }),
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET
    }),  
  ],
}
Enter fullscreen mode Exit fullscreen mode
  • To get the values of the above clientId and clientSecret, we'll go through the following process in both github and googleCloud respectively:
  • For Github, let's go to our Github
    • Navigate then through: Your profile icon(at the top right of the interface) > settings > developer settings > OAuth > New Project. And Then fill in the form this way:

register a new OAuth application

  • Next, recover the clientId highlighted below and then generate client secret.

Client ID and Secret recovery

  • For Google, let's go to our Google Cloud

    • Navigate then through: my Project(right near the logo) > Menu > API > Identifiers > Create identifier > ID client OAuth. And then do the following:
  • First select the web app as the application type

    Create an ID client Auth

  • Then, Fill in the form like this:

Identifier creation

  • Same process, by clicking on Create you'll be able to recover those keys as well.

client ID and Secret recovery

NOTE:

  • replace "weiterbildung" by the name of your project
  • Go to your existing .env file in which you'll save those keys and more sensitive informations, create it if it doesn't exist in your root directory.

Step 2. Create the Authentication API route

  • In App Create the directory api/[...nextauth]/route.ts and implement the authentication API route the following way:
// route.ts

import { authOptions } from "@/lib/authOptions";
import NextAuth from "next-auth";
import { AuthOptions } from "next-auth";

const handler = NextAuth(authOptions as AuthOptions);

export { handler as GET, handler as POST };
Enter fullscreen mode Exit fullscreen mode
  • Create a provider that will wrap your system, to make all its props available like a context, in your lib directory, create sessionWrapper.tsx where you'll do:
//sessionWrapper.tsx

"use client"

import { SessionProvider } from "next-auth/react"

const SessionWrapper = ({children}: {children: React.ReactNode}) => {
  return <SessionProvider>{children}</SessionProvider>
}

export default SessionWrapper;
Enter fullscreen mode Exit fullscreen mode
  • implement the SessionWrapper component in layout.tsx after importing it and wrap the layout elements within it, its return should look like this:
//layout.tsx
import SessionWrapper from "../lib/sessionWrapper";

//...some code
return (
    <SessionWrapper> //here you are
      <html lang="en">
        <body
          className={`${geistSans.variable} ${geistMono.variable} antialiased`}
        >
          <ClientLayout session={session}>{children}</ClientLayout>
        </body>
      </html>
    </SessionWrapper> //here you are
  );
Enter fullscreen mode Exit fullscreen mode

Step 3. Set up the connexion between your system and the google and github providers

  • In your log-in page or component do the following modification:
//logIn.tsx


"use client"

import { signIn, useSession } from 'next-auth/react';

export default function Login() {
  const { data: session } = useSession();

  if(session) {
    console.log('session', session);
  }


  return (
    <div>
          <button
            type="button"
            onClick={() => signIn('github')}
            className="w-full py-2 my-2 border border-red-500"
          >Login with Github
          </button>

          <button
            type="button"
            onClick={() => {signIn('google')}}
            className="w-full py-2 my-2 border border-red-500"
          >Login with Google
          </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
  • In your log-out component do the following modification:
//signOut.tsx


import { signOut } from 'next-auth/react';

export default function Login() {  
  return (
    <div>
          <button
            type="button"
            onClick={() => signOut()}
            className="w-full py-2 my-2 border border-red-500"
          >Log out
          </button>

    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

RESULT WITH GOOGLE:

Google result

NOTE:

  • In the console, you'll be able to see the user credential once the signIn function is triggered by any of the two buttons.
    user session result

  • You can choose to get the JWT(Json Web Token) instead of a row object if you want to get your backend involved.

💖 💪 🙅 🚩
haroldmud
Harold Mudosa

Posted on November 29, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related