在设置nexthauth v4时遇到一些问题。获取此错误:
客户端获取错误,JSON输入意外结束{错误:{…},路径:"session",消息:"JSON.parse:第1行数据意外结束JSON数据"}"的第1列。
要修复它,他们说您必须在部署时将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>
);
}
session
和jwt
回调需要分别返回一个session
和jwt
对象。您需要将每个函数中的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;
}
}