
在 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、广告合规与用户体验的最优路径。









