登录
首页 >  文章 >  前端

Next.js App Router 服务端获取用户信息方法

时间:2026-04-01 15:03:25 469浏览 收藏

在 Next.js App Router 中,由于服务端组件运行于无浏览器环境,无法访问 localStorage 等客户端 API,因此必须摒弃前端存储令牌的旧模式,转而采用更安全、更可靠的 HTTP-only Cookie 方案——登录时由后端签发并设置加密、安全、同站的 Cookie,服务端组件则通过自动携带该 Cookie 的 fetch 调用 `/api/auth/me` 预取用户信息,既保障了认证安全性(防 XSS 窃取),又实现了 SSR 下的首屏用户数据直出,完美支持 SEO、广告合规(如 AdSense)及服务端路由鉴权,真正打通了现代全栈应用中身份验证与用户体验的关键闭环。

Next.js App Router 中服务端获取认证用户信息的正确实践

在 Next.js App Router 中无法直接从服务端访问 localStorage,需改用 HTTP-only Cookie 存储令牌,并通过服务端 fetch 调用 /api/auth/me 完成身份验证与用户数据预取。

在 Next.js App Router 中无法直接从服务端访问 localStorage,需改用 HTTP-only Cookie 存储令牌,并通过服务端 fetch 调用 `/api/auth/me` 完成身份验证与用户数据预取。

在 Next.js App Router 架构下,服务端组件(Server Components)运行于边缘或 Node.js 服务端环境,完全无浏览器上下文,因此 localStorage、sessionStorage、window 等客户端 API 均不可用。你提到的 axios.get("/api/auth/me", { headers: { Authorization:Bearer ${token}} }) 方案在服务端会因无法读取 localStorage 而失败——这不是权限问题,而是根本不存在该 API。

✅ 正确解法:使用 HTTP-only + Secure Cookie 传递认证凭证
当用户登录成功后(例如通过 /api/auth/login),后端应设置一个签名、加密、且 HttpOnly: true、Secure: true、SameSite: 'lax' 的 Cookie(如 __session),该 Cookie 会随后续所有同源请求自动携带,且无法被 JavaScript 读取(增强安全性)。

服务端组件中即可安全发起带认证的 API 请求:

// app/layout.tsx —— 注意:layout 是服务端组件,默认不支持 useClient
import "./globals.css";
import { Inter } from "next/font/google";
import Sidebar from "../components/Sidebar";

const inter = Inter({ subsets: ["latin"] });

// ✅ 在 layout 中调用服务端函数获取用户(推荐放在独立服务模块中)
async function getCurrentUser() {
  try {
    const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/auth/me`, {
      method: "GET",
      headers: {
        // Cookie 由浏览器自动注入,无需手动添加 Authorization header
        // (前提是后端已正确设置 HttpOnly Cookie 且域名/路径匹配)
      },
      cache: "no-store", // 避免 SSR 缓存过期用户状态
      credentials: "include", // ⚠️ 注意:fetch 在服务端不支持 credentials 选项!
      // ✅ 正确做法:依赖底层 Node.js 或 Edge Runtime 自动转发 Cookie(Next.js 13.4+ 自动处理)
    });

    if (!res.ok) return null;
    return (await res.json()) as { id: string; email: string } | null;
  } catch (e) {
    console.error("Failed to fetch user:", e);
    return null;
  }
}

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const user = await getCurrentUser(); // ✅ 服务端预取用户数据

  return (
    <html lang="da" className="h-full bg-gray-100">
      <body className="h-full bg-gray-100">
        <Sidebar user={user} /> {/* 可将 user 透传给服务端或客户端组件 */}
        {children}
      </body>
    </html>
  );
}

? 关键注意事项:

  • credentials: "include" 在服务端 fetch 中无效:Next.js 服务端 fetch 会自动继承当前请求的 Cookie(只要 Cookie 设置正确),无需显式配置。请确保你的 /api/auth/me 路由能从 request.headers.get("cookie") 中解析出有效 session。

  • 后端 Cookie 设置示例(Next.js Route Handler)

    // app/api/auth/login/route.ts
    import { cookies } from "next/headers";
    
    export async function POST(req: Request) {
      const body = await req.json();
      const { token } = await authenticate(body); // 你的鉴权逻辑
    
      cookies().set({
        name: "__session",
        value: token,
        httpOnly: true,
        secure: process.env.NODE_ENV === "production",
        sameSite: "lax",
        path: "/",
        maxAge: 60 * 60 * 24 * 7, // 7 days
      });
    
      return Response.json({ success: true });
    }
  • 广告兼容性保障:因用户数据在服务端完成获取与渲染,SSR 页面可安全集成 Google AdSense(无需等待客户端 hydration),满足广告展示对首屏内容可见性的要求。

  • 安全强化建议:始终对 /api/auth/me 做服务端 session 校验(如 JWT 验证或 Redis 查表),切勿仅依赖前端传参;同时启用 middleware.ts 进行路由级鉴权(如保护 /dashboard/*)。

总结:放弃 localStorage 依赖,拥抱 Cookie 驱动的服务端认证流,是 App Router 下兼顾安全性、SEO、广告合规与用户体验的最优路径。

以上就是《Next.js App Router 服务端获取用户信息方法》的详细内容,更多关于的资料请关注golang学习网公众号!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>