You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 13中page.js文件如何获取Session?

Next.js 13 中 API 路由获取 Session 数据的解决方案

先明确核心差异:Next.js 13 的两种路由体系

Next.js 13 同时支持传统的 Pages Router 和新的 App Router,两者获取 Session 的方式完全不同,先对应你的项目类型调整:


1. 如果你仍在使用 Pages Router(和 Next.js 12 结构一致)

getSession 依然可用,但要确保在 API 路由中正确传入 req 和 res 参数:

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

export default async function handler(req, res) {
  // 必须传入 { req } 才能正确获取会话
  const session = await getSession({ req });
  
  if (!session) {
    return res.status(401).json({ message: "未授权" });
  }
  
  // 后续业务逻辑,比如用 session.user.id 查询数据
  res.status(200).json({ data: "你的数据", user: session.user });
}

如果还是只能拿到初始数据,检查:

  • 是否在 _app.js 中用 SessionProvider 包裹了页面
  • NextAuth 配置中的 session.strategy 是否正确(JWT 或数据库)

2. 如果你使用新的 App Router

App Router 的 API 路由是 Server Component,无法直接用 getSession,需要用 NextAuth v4 提供的 auth() 函数:

步骤1:配置 NextAuth 路由

在 app/api/auth/[...nextauth]/route.js 中配置认证:

import NextAuth from "next-auth";
// 替换成你用的认证提供商,比如 Credentials、Google 等
import CredentialsProvider from "next-auth/providers/credentials";

const handler = NextAuth({
  providers: [
    CredentialsProvider({
      name: "Credentials",
      async authorize(credentials) {
        // 这里写你的用户验证逻辑,返回用户对象
        const user = { id: "1", name: "test" };
        return user;
      },
    }),
  ],
  // 推荐用 JWT 策略,适配 App Router
  session: { strategy: "jwt" },
  callbacks: {
    // 把用户信息注入 JWT
    async jwt({ token, user }) {
      if (user) {
        token.id = user.id;
      }
      return token;
    },
    // 把 JWT 数据同步到 Session
    async session({ session, token }) {
      session.user.id = token.id;
      return session;
    },
  },
});

export { handler as GET, handler as POST };

步骤2:在其他 API 路由中获取 Session

创建单独的 auth 导出文件(比如 app/api/auth/[...nextauth]/auth.js):

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

export default auth;

然后在目标 API 路由中使用:

import auth from "@/app/api/auth/[...nextauth]/auth";

export async function GET(request) {
  const session = await auth();
  
  if (!session) {
    return new Response(JSON.stringify({ message: "未授权" }), { status: 401 });
  }
  
  // 处理业务逻辑
  return new Response(JSON.stringify({ session }), { status: 200 });
}

关于 useSession 只能获取初始数据的问题

useSession 是客户端钩子,只能在 标记为 "use client" 的组件中使用,且必须用 SessionProvider 根包裹:

"use client";

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

export default function RootLayout({ children }) {
  return (
    <html lang="zh-CN">
      <body>
        <SessionProvider>{children}</SessionProvider>
      </body>
    </html>
  );
}

如果需要实时更新 Session,可开启 refetchOnWindowFocus:

<SessionProvider refetchOnWindowFocus>{children}</SessionProvider>

内容的提问来源于stack exchange,提问作者Jayesh karma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 20:45:37