ProNextJS

    How Do I Use Next-Auth With The App Router?

    Jack HerringtonJack Herrington

    Question: How do I use Next-Auth?

    Answer: Great question, and hopefully I have a fairly straightforward answer for you. First off Next-Auth is a library, not a authentication service provider (e.g. GitHub, Google, Facebook, Apple, etc.). So you are going to have to integrate with one of those, or provide a database adapter to your own database of users. Thankfully the integration is pretty easy.

    Let's try out integrating with GitHub. The first thing you are going to want to do is to get yourself an OAuth token. To do that, start by going to the Developer Settings sections of your Settings page. From there click on OAuth Apps menu item and then click the Register a new application button.

    From here you name your application. For the Homepage URL field use http://localhost:3000/ and then for the Authorization callback URL use http://localhost:3000/api/auth/callback/github. You'll want to have two of these tokens, one for development, which is what we just created. And another for production.

    When you hit Register application you'll go to another page that has a client ID, that you need to copy and paste into a .env file in your App Router NextJS application with the name GITHUB_ID. And then get the secret key and put that into the .env file as the GITHUB_SECRET key.

    Now we are all set up and we can create install next-auth by running:

    pnpm add next-auth
    

    Or whatever package manager you use.

    Now we need to create the API callback that we configured on the GitHub OAuth account. To do that we create a new API route in /app/api/auth/[...nextauth]/route.ts, with the contents:

    import NextAuth from "next-auth";
    import GitHubProvider from "next-auth/providers/github";
    
    export const options = {
      providers: [
        GitHubProvider({
          clientId: process.env.GITHUB_ID ?? "",
          clientSecret: process.env.GITHUB_SECRET ?? "",
        }),
      ],
    };
    
    export const handler = NextAuth(options);
    
    export { handler as GET, handler as POST };
    

    Now restart the application and go to /api/auth/signin and you should get a login provider selector page. Click on the GitHub button and go through the flow and you should be returned to your home page with a session.

    You can create an AuthButton component to put some UI on this, like so:

    "use client";
    import { signIn, signOut, useSession } from "next-auth/react";
    
    export default function AuthButton() {
      const { data: session } = useSession();
    
      if (session) {
        return (
          <>
            {session?.user?.name} <br />
            <button onClick={() => signOut()}>Sign out</button>
          </>
        );
      }
      return (
        <>
          Not signed in <br />
          <button onClick={() => signIn()}>Sign in</button>
        </>
      );
    }
    

    Add AuthButton to your layout.tsx file and now you can sign in and sign out with ease. And you can get the details for the currently logged in user from either useSession in a client component or getServerSession in an RSC.

    Subscribe for Free Tips, Tutorials, and Special Discounts

    We're in this together!

    I respect your privacy. Unsubscribe at any time.