ProNextJS
    Loading
    lesson

    NextAuth v5 Update

    Jack HerringtonJack Herrington

    NextAuth v5 has been released, and there are some changes that affect the Next.js App Router. While the authorization code we've seen so far is similar, there have been some significant changes to the NextAuth API. The code on GitHub is always current with these updates.

    Moving the Auth Configuration

    The most significant change is that the auth configuration has been moved into a file called auth.ts, located in the src folder at the top level. This file contains all of the configuration options we've seen before, but at the bottom of the file, we now have access to new functions.

    • signIn and signOut functions from NextAuth, used for the user button
    • auth function, used throughout the application to get the current session
    • handlers, used in the API route
    // at the bottom of src/auth.ts
    
    export const { handlers, auth, signIn, signOut }  = NextAuth(authOptions);
    

    Simplifying the API Route

    The API route for auth has been greatly simplified. It now imports the handlers from the auth.ts file using the path @/auth, and then exports the GET and POST methods from those handlers:

    // inside src/app/api/auth/[...nextauth]/route.ts
    import { handlers } from '@/auth';
    
    export const { GET, POST } = handlers;
    

    Layout Changes

    There are also a few changes to the layout. At the top of the file, instead of bringing in our own session provider that we had to wrap, we now import it directly from next-auth/react. We also import signIn, signOut, and auth from our auth.ts file:

    // inside src/app/layout.tsx
    import { SessionProvider } from 'next-auth/react';
    import { signIn, signOut, auth } from '@/auth';
    

    In the layout, we retrieve the current authorization and set up the user session. We extract the sensitive information from the session and only include the person's name, email, and image for the avatar:

    // inside RootLayout component in src/app/layout.tsx
    
    const session = await auth();
    if (session?.user) {
      session.user = {
        name: session.user.name,
        email: session.user.email,
        image: session.user.image,
      };
    }
    

    The SessionProvider has been updated to require a basePath and the session:

    <SessionProvider basePath="/api/auth" session={session}>
      {/* ... */}
    </SessionProvider>
    

    The UserButton now accepts onSignIn and onSignOut server actions, which wrap the signIn and signOut functions:

    // components/user-button.tsx
    export default function UserButton({
      onSignIn,
      onSignOut,
    }: {
      onSignIn: () => Promise<void>;
      onSignOut: () => Promise<void>;
    }) {
      // ...
    }
    

    Updating Server Information

    In any page that needs server information, we previously called getServerSession. Now, we call the auth function. We can alias auth to getServerSession and call it the same way:

    // inside src/app/chats/[chatId]/page.tsx
    import { auth as getServerSession } from '@/auth';
    

    Middleware Changes

    Later in the course, we use middleware to protect the /chats route, which is the detail route when you go into a chat. The code here has also been updated, but the underlying logic remains the same, just with some different API calls.

    // src/middleware.ts
    
    import { NextResponse } from "next/server";
    import { auth } from "@/auth";
    
    export const config = {
      matcher: ["/chats/:chatidx"],
    };
    
    export default auth((req) => {
      if (!req.auth) {
        return NextResponse.redirect(new URL("/api/auth/signin", req.url));
      }
    });
    

    Keeping Up with Changes

    It's important to note that these libraries - Next.js, NextAuth, and others - are constantly evolving. While it may be inconvenient, the code in the repository is always the most up-to-date. Throughout the course, there will be occasional videos like this one to address these changes as they occur.

    Transcript

    Hi. There have been some changes in NextAuth as it relates to the Next.js AppWriter. And as they're going into the next version of NextAuth, I wanted to keep all the code up to date with where they're going. So what you've seen so far in the authorization section is pretty close, but there were some fairly dramatic changes to the NextAuth API, and the code that's on GitHub is of course always up-to-date with all that. I do want to walk you through a little bit of it just to kind of get you reoriented with where the code has moved around to.

    So the most important thing is that the auth configuration has now moved into a file called auth.ts. It's in the source folder right at the top and it contains all of the configuration options as you've seen. The big difference is down at the bottom where we expose a couple of new things. We now have sign in and sign out functions from NextAuth. We use those for the user button.

    You've got this auth function that you use pretty much everywhere to get the current session. And then we've got handlers, which we use over in the API route. Now the API route is much simplified. So the API route for Auth is simply now importing the handlers from that Auth file at slash Auth which means slash source slash Auth and then we export the get and post from those handlers. There are a few changes to the layout as well.

    Right at the top instead of bringing in our own session provider that we had to wrap, we now just bring it in from NextAuthReact. Woo! Awesome! We're also going to sign in and sign out an auth from auth and I'll show you where they're used. Right at the top of the layout we're going to get the current authorization and then we're going to set up the user session.

    And to do that, we're actually going to go and pull out any kind of sensitive information from that and just put into the session the person's name, email, and image for the avatar. The session provider has changed a little bit. We have to give it a base path now and the session, and the user button has changed. Now we get to give it server actions for onSignIn and onSignOut, and really those just wrap sign in and sign out. The user button has changed a little bit just to go and bring in those new server actions and invoke those instead of sign in and sign out from NextAuthReact.

    Any page that needs your server information used to call getServerSession. We now call auth. So in this case, we're just aliasing auth to getServerSession and then calling it exactly the same way. Later on in the course, we use middleware to protect the slash chats route, which is the detail route for when you go into a chat. The code there has changed a little bit too, but nothing outside of the logic that we had there before, just some different API.

    I know it's inconvenient, but these things change. Next.js is changing, Next.auth is changing, all of these libraries are changing. The code in the repo is always the most up to date, and I'll be doing videos like these sprinkled throughout here or there, hopefully not a lot of them, that go and handle those changes as we see them. All right, keep on enjoying getting started, and I'll see you in the next video.