DEV Community

Cover image for Mastering Next-Auth: Your Comprehensive Guide to Next.js Authentication
Ian Kamau
Ian Kamau

Posted on

Mastering Next-Auth: Your Comprehensive Guide to Next.js Authentication

NextAuth.js is a complete open-source authentication solution for Next.js applications. It is designed from the ground up to support Next.js and Serverless

NextAuth has authentication providers that allow your users to sign in with their favorite preexisting logins. You can use any of our many predefined providers, or write your own custom OAuth configuration.

In this blog, we will use NextAuth to authenticate using Google

To begin, you need to have already set up a Nextjs application.
First thing to do is to install next-auth using this command

npm install next-auth
Enter fullscreen mode Exit fullscreen mode

Add API route

To add NextAuth.js to a project create a file called route.ts in /app/api/auth/[...nextauth]/

/app/api/auth/[...nextauth]/route.ts

We want all routes pointing to app/api/auth/ to be caught that is why we use [...nextauth]

In /app/api/auth/[...nextauth]/route.ts, add the following code

// src/app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

// Define your NextAuth options
const authOptions = {
  // Configure one or more authentication providers
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_API_SECRET!,
      authorization: {
        params: {
          prompt: "consent",
          access_type: "offline",
          response_type: "code",
        },
      },
    }),
  ],
  // ...add more providers here
};

// Create the NextAuth handler
const handler = NextAuth(authOptions);

// Export the handler for both GET and POST requests
export const GET = handler;
export const POST = handler;

Enter fullscreen mode Exit fullscreen mode

Create .env.local

You can get both GOOGLE_CLIENT_ID and GOOGLE_API_SECRET in https://console.cloud.google.com/apis/dashboard

GOOGLE_CLIENT_ID="<YOUR GOOGLE CLIENT ID>"
GOOGLE_API_SECRET="<YOUR GOOGLE API SECRET>"
Enter fullscreen mode Exit fullscreen mode

Configure Shared session state

You will need your children in app/layout.tsx with

It should look like this

"use client"
import { Inter } from "next/font/google";
import "./globals.css";
import { SessionProvider } from "next-auth/react";

const inter = Inter({ subsets: ["latin"] });
import "./globals.css";

export default function RootLayout({
  children,
}: Readonly<{ children: React.ReactNode}>) {
  return (
    <html lang="en">
      <body className={inter.className}>
          <SessionProvider refetchInterval={5 * 60}>
            {children}
          </SessionProvider>
      </body>
    </html>
  );
}

Enter fullscreen mode Exit fullscreen mode

By using refetchinterval you ensure that the session data is refetched every 5 minutes, which helps in maintaining the accuracy and security of the session state in your Next.js application

Frontend - Add React Hook

We have done with all the configurations, the only thing remaining is to add the sign up and sign out buttons

We use the useSession() React Hook in the NextAuth.js client to sign in, check if someone is signed in and sign out.

In components/navbar.tsx import useSession() and add the following code

import { useSession, signIn, signOut } from "next-auth/react"

export default function Navbar() {
  const { data: session } = useSession()
  if (session) {
    return (
      <>
        Signed in as {session.user.email} <br />
        <button onClick={() => signOut({callbackUrl: "/"})}>Sign out</button>
      </>
    )
  }
  return (
    <>
      Not signed in <br />
      <button onClick={() => signIn("google")}>Sign in</button>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

we can get current user's information from the data provided here const { data: session } = useSession()

With that, you users can successfully login using their google accounts

Top comments (0)