Updated NextAuth from v3 to v4

lada496

Yuko

Posted on May 28, 2023

Updated NextAuth from v3 to v4

This is a series of my memo from when I migrated Next.js v13 into my project with the article From Pages to App. I also updated other packages’ versions.

Part1: Migrated app router from page router

Part2: Migrated router API

Part3: Applied some other Next.js v13 updates

Optional: Updated NextAuth from v3 to v4

Optional: Updated Redux from classical Redux to Redux Toolkit Query

Updated pages/app/auth/[…nextauth].js

    // Before
    import NextAuth from "next-auth";
    import Providers from "next-auth/providers";
    import { verifyPassword } from "../../../lib/auth-utils";
    import { connectToDatabase } from "../../../lib/db-utils";

    export default NextAuth({
      session: {
        jwt: true,
      },
      providers: [
        Providers.Credentials({
          async authorize(credentials) {
            const client = await connectTatabase();

            const usersCollection = client.db().collection("users");

            const user = await usersCollection.findOne({
              email: credentials.email,
            });

            if (!user) {
              client.close();
              throw new Error("No user found!");
            }

            const isValid = await verifyPassword(
              credentials.password,
              user.password
            );

            if (!isValid) {
              client.close();
              throw new Error("Could not log you in!");
            }

            client.close();
            return { email: user.email };
          },
        }),
      ],
    });
Enter fullscreen mode Exit fullscreen mode
    // After
    import NextAuth from "next-auth";
    import CredentialsProvider from "next-auth/providers/credentials";
    import { verifyPassword } from "../../../lib/auth-utils";
    import { connectToDatabase } from "../../../lib/db-utils";

    const authOptions = {
      session: {
        jwt: true,
      },
      secret: process.env.NEXTAUTH_SECRET,
      providers: [
        CredentialsProvider({
          async authorize(credentials) {
            const client = await connectToDatabase();

            const usersCollection = client.db().collection("users");

            const user = await usersCollection.findOne({
              email: credentials.email,
            });

            if (!user) {
              client.close();
              throw new Error("No user found!");
            }

            const isValid = await verifyPassword(
              credentials.password,
              user.password
            );

            if (!isValid) {
              client.close();
              throw new Error("Could not log you in!");
            }

            client.close();
            return { email: user.email };
          },
        }),
      ],
    };

    export default NextAuth(authOptions);
Enter fullscreen mode Exit fullscreen mode

Update API

useSession

  • v3: Provides array, [session, loading]. Import from next-auth/client

  • v4: Provides an object having data and status properties. Import from next-auth/react

    // Before
    import { useEffect } from "react";
    import { useSelector } from "react-redux";
    import { useRouter } from "next/router";
    import { useSession } from "next-auth/client";

    const WishListPage = (props) => {
      const router = useRouter();
      const session = useSession();
      const wishlist = useSelector((state) => state.wishlist);

      useEffect(() => {
        if (!session[0]) {
          router.replace("/auth");
        }
      }, [session, router]);

      ...rest
    };
Enter fullscreen mode Exit fullscreen mode
    "use client";
    import { useEffect } from "react";
    import { useSession } from "next-auth/react";
    import { redirect } from "next/navigation";

    const WishListPage = () => {
      const { data: session } = useSession();

      if (!session) {
        redirect("/auth");
      }
      ...rest
    };

    export default WishListPage;
Enter fullscreen mode Exit fullscreen mode

getSession

  • v3: Provides session and pass {req} when using server side

  • v4: return value is the same as v3. getServerSession replace v3 getSession on server side. getServerSession receives req, res and authOption

    // Before
    import { getSession } from "next-auth/client";

    async function handler(req, res) {
      const session = await getSession({ req: req });
      if (!session) {
        res.status(401).json({ message: "Not authenticated!" });
        return;
      }
    ...rest
    }
Enter fullscreen mode Exit fullscreen mode
    // After
    import { getServerSession } from "next-auth";
    import authOptions from "../auth/[...nextauth]";


    async function handler(req, res) {
      const session = await getServerSession(req, res, authOptions);
      if (!session) {
        res.status(200).json({ message: "Not authenticated!", wishlist: [] });
        return;
      }
    ...rest
    }
Enter fullscreen mode Exit fullscreen mode

signIn, sighOut

import from next-auth/react

    // Before
    import { useSession, signOut } from "next-auth/client";

    // After
    import { useSession, signOut } from "next-auth/react";
Enter fullscreen mode Exit fullscreen mode

original article is here

💖 💪 🙅 🚩
lada496
Yuko

Posted on May 28, 2023

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

Sign up to receive the latest update from our blog.

Related