下一个身份验证的会话始终为空

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

我在 /api/getPost/[id]/route.ts 有一个 Next.jsAPI 路由。当我尝试在此路由中使用await auth() 获取会话时,它总是返回null。在成功检索会话的其他 API 路由、SSR 页面或 CSR 页面中不会出现此问题。但是,会话在 /api/getPost/[id]/route.ts 中始终返回 null。为什么会发生这种情况? 我正在使用以下版本的框架/库。

“下一个”:“14.2.16”,(应用程序路由器)

“下一个验证”:“^5.0.0-beta.25”,

// /api/getPost/[id]/route.ts

import { db } from "@/app/lib/db";
import { PostTypes } from "@/app/lib/definitions";
import { ResultSetHeader } from "mysql2";
import { auth } from "@/auth";
import { NextRequest, NextResponse } from "next/server";

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  const post_id = params.id;
  if (!post_id) {
    return NextResponse.json({ error: "Post ID is required" }, { status: 400 });
  }
  const session = await auth();
  console.log("session = ",session); // session is always null
 // ... some codes...
}
// API route where the session works"
// /api/getComments/route.ts
export async function GET(
  request: Request
): Promise<NextResponse<InfiniteQueryResponse<CommentsTypes[]>>> {
  const session = await auth();
  console.log("session = ",session); // The session returns the correct value.
  // ...codes ...
// auth.ts
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { getUser } from "./app/lib/data";

export const { handlers, auth } = NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    }),
  ],
  callbacks: {
    async signIn({ profile, user }) {
      const [isExistingUser] = await getUser(profile?.sub as string);
      console.log("isExistingUser = ", isExistingUser);
      if (!isExistingUser) {
        user.isNewUser = true;
      } else {
        user.nickname = isExistingUser.nickname;
      }
      return true;
    },
    async jwt({ token, account, profile, user, trigger, session }) {
      if (account && profile) {
        token.sub = profile.sub as string;
        token.name = profile.name;
        token.email = profile.email;
      }
      if (user) {
        token.isNewUser = user.isNewUser;
        token.nickname = user.nickname;
      }

      if (trigger === "update" && session !== null) {
        return { ...session.user };
      }

      return token;
    },
    async session({ session, token }) {
      if (session.user) {
        session.user.id = (token.sub || token.id) as string;
        session.user.isNewUser = token.isNewUser as boolean;
        session.user.nickname = token.nickname as string;
      }
      return session;
    },
  },
  pages: {
    signIn: "/login",
    newUser: "/sign-up",
  },
});

// ./middleware.ts
import { NextResponse } from "next/server";
import { auth } from "./auth";

export default auth((req) => {
  const isLoggedIn = !!req.auth;
  const PostPage = req.nextUrl.pathname.startsWith("/post");
  const MyPage = req.nextUrl.pathname.startsWith("/mypage");

  if ((PostPage || MyPage) && !isLoggedIn) {
    return NextResponse.redirect(new URL("/login", req.url));
  }
});

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|.*\\.png$).*)"],
};
reactjs next.js next-auth
1个回答
0
投票

使用 auth.ts 文件中的 auth 方法将其包装

import { auth } from "auth"

export const GET = auth(async function GET(request: Request) {
    // @ts-ignore
    const { auth } = request
    // @ts-ignore
    console.log("session (API routes)", auth)
})

了解更多信息https://authjs.dev/getting-started/session-management/protecting

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