新版本NextJS出现意外错误

问题描述 投票:0回答:1

使用 Next-Auth 和新版本的 Next.JS(版本 15)出现错误。

文件:

import { authOptions } from "@/lib/auth";
import styles from "./styles.module.scss";
import Link from "next/link";
import { AiOutlineUser } from "react-icons/ai";
import { getServerSession } from "next-auth";

export const LoginOrHello = async () => {
    const session = await getServerSession(authOptions);

    return (
        <Link href={session ? "#" : "/login"} className={styles.iconLink}>
            <AiOutlineUser />
            <span>{session ? `Hello, ${session.user.email}` : "LOGIN"}</span>
        </Link>
    );
};

import { setCookie } from "@/helpers/setCookie";
import { NextAuthOptions } from "next-auth";
import NextAuth from "next-auth/next";
import CredentialsProvider from "next-auth/providers/credentials";
import GoogleProvider from "next-auth/providers/google";
import { cookies } from "next/headers";

export const authOptions: NextAuthOptions = {
    providers: [
        CredentialsProvider({
            name: "Credentials",
            credentials: {
                email: { label: "Email", type: "email", placeholder: "Email" },
                password: {
                    label: "Password",
                    type: "password",
                    placeholder: "Password",
                },
                rememberMe: {
                    label: "Remember Me",
                    type: "checkbox",
                    placeholder: "Remember Me",
                },
            },
            async authorize(credentials) {
                if (!credentials?.email || !credentials?.password) {
                    return null;
                }

                try {
                    const res = await fetch(
                        `${process.env.NEXT_PUBLIC_API_URL}/auth/login`,
                        {
                            method: "POST",
                            headers: {
                                "Content-Type": "application/json",
                            },
                            body: JSON.stringify({
                                ...credentials,
                                rememberMe:
                                    credentials.rememberMe === "true"
                                        ? true
                                        : false,
                            }),
                        }
                    );

                    const data = await res.json();

                    (await cookies()).set("token", data.token);

                    if (data.error) {
                        return { status: data?.status, error: data?.message };
                    }

                    return data;
                } catch (error) {
                    return error;
                }
            },
        }),
        GoogleProvider({
            clientId: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID as string,
            clientSecret: process.env
                .NEXT_PUBLIC_GOOGLE_CLIENT_SECRET as string,
        }),
    ],
    callbacks: {
        async jwt({ token, user, account, profile }) {
            if (account?.provider === "google" && account.access_token) {
                try {
                    const res = await fetch(
                        `${process.env.NEXT_PUBLIC_API_URL}/auth/google-login`,
                        {
                            method: "POST",
                            headers: {
                                "Content-Type": "application/json",
                            },
                            body: JSON.stringify({
                                token: account.access_token,
                            }),
                        }
                    );

                    const data = await res.json();
                    (await cookies()).set("token", data.token);

                    if (res.ok && data?.token) {
                        token.id = data.id;
                        token.email = data.email;
                        token.token = data.token;
                    } else {
                        throw new Error(
                            "Failed to exchange Google token for backend JWT"
                        );
                    }
                } catch (error) {
                    console.error("Error exchanging Google token:", error);
                }
            }

            if (user) {
                token.id = user.id;
                token.email = user.email || "";
                token.token = user.token;
            }

            return token;
        },
        async signIn({ user }: any) {
            if (user?.error) {
                throw new Error(user?.error);
            }
            return true;
        },
        async session({ session, token }) {
            if (token) {
                session.user.id = token.id!;
                session.user.email = token.email!;
                session.user.token = token.token;
            }
            return session;
        },
    },
    secret: process.env.NEXT_PUBLIC_NEXTAUTH_SECRET,
    jwt: {
        secret: process.env.NEXT_PUBLIC_NEXTAUTH_SECRET,
    },
    session: {
        strategy: "jwt",
    },
    pages: {
        signIn: "/login",
    },
};

import NextAuth, { DefaultSession, DefaultUser } from "next-auth";
import { JWT as NextAuthJWT } from "next-auth/jwt";

declare module "next-auth" {
    interface User extends DefaultUser {
        id: string;
        token?: string;
    }

    interface Session {
        user: {
            id: string;
            email: string;
            token?: string;
        } & DefaultSession["user"];
    }
}

declare module "next-auth/jwt" {
    interface JWT extends NextAuthJWT {
        id: string;
        email: string;
        token?: string;
    }
}

从“@/lib/auth”导入{authOptions}; 从“next-auth/next”导入 NextAuth;

常量处理程序 = NextAuth(authOptions);

export { 处理程序为 GET,处理程序为 POST };

enter image description here enter image description here

意外错误,我不知道如何修复它。很确定这个问题与新版本的 Next.JS 有关,因为使用以前的版本(14.x.x)没有问题

reactjs next.js next-auth
1个回答
0
投票

您遇到的错误很可能是由于没有等待而导致的

cookies()

查看错误消息指向的文档页面,您正在同步调用

cookies() 
,但它现在返回一个必须等待的承诺。

尝试将您的调用包装在异步函数中。像这样的东西:

import { cookies } from 'next/headers';

export default async function AddressesPage() {
  const allCookies = (await cookies()).getAll();
  // Rest of your code
}
© www.soinside.com 2019 - 2024. All rights reserved.