NextAuth 在会话回调中抛出 CLIENT_FETCH_ERROR 错误

NextAuth throwing CLIENT_FETCH_ERROR error in session callback

设置 nextauth v4 时遇到一些问题。得到这个 error:

Client fetch error, Unexpected end of JSON input {error: {…}, path: 'session', message: 'JSON.parse: unexpected end of data at line 1 column 1 of the JSON data'}.

要修复它,他们说您必须在部署时将 url 路径添加到 .env 文件。我在localhost上工作,所以这应该不是问题,但是添加之后,仍然是同样的错误。

当我注释掉 [...nextauth] 文件中的异步会话回调时,错误不会弹出,会话已“通过身份验证”但不会持续存在。我已经盯着它看了好一阵子了,需要一些帮助!

[...nextauth].js

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export default NextAuth({
  providers: [
    CredentialsProvider({
      async authorize(credentials, res) {

        //find existing user
        const user = await prisma.user.findUnique({
          where: {
            email: credentials.email,
          },
        });

        if (
          credentials.email === user.email &&
          credentials.password === user.password
        ) {
          return user;
        } else {
          return res.status(409).send({ message: "No user with that email." });
        }
      },
    }),
  ],
  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.id = user.id;
        return token;
      }
    },
    //commenting this function and no error shows up
    async session({ session, token }) {
      if (token) {
        session.id = token.id;
        return session;
      }
    },
  },
  secret: "mysecret",
  jwt: {
    secret: "mysecret",
    encryption: true,
  },
  session: {
    strategy: "jwt",
    maxAge: 1 * 24 * 60 * 60,
  },
});

auth-form

import { signIn, useSession } from "next-auth/react";

export default function AuthForm() {
  const { data: session } = useSession();

  const handleSubmit = async (userData) => {
    const { error, ok, url } = await signIn("credentials", {
      redirect: false,
      email: userData.email,
      password: userData.password,
      callbackUrl: "/profiel",
    });

    if (ok) {
      router.push(url);
    } else {
      alert(error);
    }
  };

  return (
      <Form onSubmit={handleSubmit}>
        <Field id="email" />
        <Field id="password" />
        <button type="submit">{isRegistered ? "Sign in" : "Register"}</button>
      </Form>
  );
}

_app.js

import { SessionProvider } from "next-auth/react";

function MyApp({ Component, pageProps: { session, ...pageProps } }) {
  return (
    <SessionProvider session={session}>
      <Component {...pageProps} />
    </SessionProvider>
  );
}

sessionjwt 回调需要分别 return 一个 sessionjwt 对象。您需要将每个函数中的 return 语句移动到 if 块之后。

callbacks: {
    async jwt({ token, user }) {
        if (user) {
            token.id = user.id;
        }
        return token;
    },
    async session({ session, token }) {
        if (token) {
            session.id = token.id;
        }
        return session;
    }
}