Updated NextAuth from v3 to v4
Tags: nextjs, react
Published: 2023-05-28 07:54:22

This is a series of my memo from when I migrated Next.js v13 into my project with the article [From Pages to App](https://nextjs.org/docs/pages/building-your-application/upgrading/app-router-migration#migrating-_documentjs-and-_appjs). I also updated other packages’ versions.

[Part1: Migrated app router from page router](https://medium.com/@lada496/updated-my-next-js-project-to-v13-part1-migrated-app-router-27c3ce172bba)

[Part2: Migrated router API](https://medium.com/@lada496/updated-my-next-js-project-to-v13-part2-hooks-for-app-router-38a82a8e5b0)

[Part3: Applied some other Next.js v13 updates](https://medium.com/@lada496/updated-my-next-js-project-to-v13-part2-link-use-client-3f5e17d12b8f)

**Optional: Updated NextAuth from v3 to v4**

[Optional: Updated Redux from classical Redux to Redux Toolkit Query](https://medium.com/@lada496/optimistic-updates-with-rtk-query-4770698de6c1)

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

* Export authOption to use in other files ([getServerSession](https://next-auth.js.org/configuration/nextjs#getserversession)[​](https://next-auth.js.org/configuration/nextjs#getserversession))

* Provider.Credentials → CredentialsProvier ([Credentials](https://next-auth.js.org/configuration/providers/credentials))

* Add secret property for jwt ([NEXTAUTH_SECRET](https://next-auth.js.org/configuration/options#nextauth_secret))
```javascript
    // 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 };
          },
        }),
      ],
    });
```
```javascript
    // 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);
```

## 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
```javascript
    // 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
    };
```
```javascript
    "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;
```
### 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
```javascript
    // 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
    }
```
```javascript
    // 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
    }
```
### signIn, sighOut
```javascript
import from next-auth/react

    // Before
    import { useSession, signOut } from "next-auth/client";
    
    // After
    import { useSession, signOut } from "next-auth/react";
```
original article is [here](https://medium.com/@lada496/updated-nextauth-from-v3-to-v4-4210f2b994e3)