使用 NextAuth 时 auth.js v5 route.ts 文件中出现空会话问题

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

我在使用 authjs v5 时遇到这个问题。

这是我的

route.ts
文件

import { auth } from "@/auth";
import { db } from "@/lib/db";
import { NextRequest, NextResponse } from "next/server";

export async function GET(req: NextRequest) {
    try {
        const session = await auth();
        console.log(session, "session");
        
        if (!session) {
            return NextResponse.json({ user: null, message: 'Unauthorized' }, { status: 401 });
        }
        const id = Number(session?.user?.id);
        const user = await db.user.findUnique({
            where: { id }
        });
        if (!user) {
            return NextResponse.json({ user: null, message: 'User not found' }, { status: 404 });
        }
        const { password, ...userData } = user;
        return NextResponse.json({ user: userData, message: 'User found' }, { status: 200 });
    } catch (error: any) {
        return NextResponse.json({ error: error.message, message: "Something went wrong!" }, { status: 500 });
    }
}

在记录会话时我总是得到

null
,但它在我的服务器组件中有效。

以下是我的

auth.ts
文件:

import { PrismaAdapter } from "@auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";
import NextAuth from "next-auth";
import authConfig from "./auth.config";
const prisma = new PrismaClient()

export const { handlers, auth, signIn, signOut } = NextAuth({
    adapter: PrismaAdapter(prisma),
    secret: process.env.AUTH_SECRET,
    session: { strategy: "jwt" },
    callbacks: {
        async session({ session, token }) {
            if (!token) {return session;}
            if (session.user && token.sub) {
                session.user.id = token.sub;}
            return session;
        },
        async jwt({ token, user }) {
            if (user) {
                token.id = user.id;
            }
            return token;}},
    ...authConfig,})

这是我的

auth.config.ts
文件

import { NextAuthConfig } from "next-auth";
import Credentials from "next-auth/providers/credentials";
import { db } from "./lib/db";
import { LoginSchema } from "./schemas/user-schema";
import { hash } from "./utils/bcrypt";

export default {
    providers: [
        Credentials({
            credentials: {
                email: { label: "Email", type: "email" },
                password: { label: "Password", type: "password" }
            },
            async authorize(credentials) {
                const validateFields = LoginSchema.safeParse(credentials);
                if (!validateFields.success) {
                    return null;
                }
                const { email, password } = validateFields.data;
                const isUser = await db.user.findUnique({
                    where: {
                        email
                    }
                })
                if (!isUser) {
                    return null;
                }
                if (hash(password) === isUser.password){
                    return isUser as any;
                }
                return null;
            }
        })
    ],
} satisfies NextAuthConfig

我希望它能够通过会话获取 id 并从数据库获取数据,会话在服务器组件中工作,但在 API 路由中不起作用

session next.js next-auth credential-providers
1个回答
0
投票

嗨,我刚刚遇到这个问题。我发现添加下一个标头可以使其工作。

import { headers } from "next/headers"

const res = await fetch("api/post", {
  headers: headers()
})

© www.soinside.com 2019 - 2024. All rights reserved.