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

Next.js 13路由JWT令牌校验及认证逻辑实现求助

Next.js 13 + Express 认证实现方案

原代码的问题点

  • 请求头中的令牌是字符串字面量 "authToken",而非实际获取到的变量,导致后端无法验证有效令牌
  • 缺失错误处理逻辑,令牌无效或不存在时未执行跳转
  • authToken 状态未实际使用,属于冗余代码

可复用认证工具函数

创建 utils/auth.ts 文件,封装通用认证逻辑:

"use client";

import axios from "axios";
import { useRouter } from "next/navigation";

// 验证令牌有效性,失败则跳转登录页
export async function verifyAuth() {
  const router = useRouter();
  const authToken = localStorage.getItem("x-auth-token");

  // 无令牌直接跳转登录
  if (!authToken) {
    router.push("/login");
    return null;
  }

  try {
    // 发送令牌到后端验证
    const response = await axios.get(
      `${process.env.NEXT_PUBLIC_SERVER_URL}/api/user`,
      {
        headers: { "x-auth-token": authToken },
      }
    );
    return response.data; // 返回验证通过的用户信息
  } catch (error) {
    // 令牌无效或请求失败,清除无效令牌并跳转
    localStorage.removeItem("x-auth-token");
    router.push("/login");
    return null;
  }
}

页面组件中使用示例

修改 app/page.tsx(Next.js 13 App Router):

"use client";

import { useEffect, useState } from "react";
import { verifyAuth } from "@/utils/auth";

export default function Home() {
  const [userProfile, setUserProfile] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    async function fetchUserProfile() {
      const profile = await verifyAuth();
      if (profile) setUserProfile(profile);
      setIsLoading(false);
    }

    fetchUserProfile();
  }, []);

  if (isLoading) {
    return <p>加载中...</p>;
  }

  // 仅在认证通过后渲染页面内容
  return (
    <div>
      <h1>欢迎回来,{userProfile.username}!</h1>
      {/* 其他页面内容 */}
    </div>
  );
}

客户端/服务端组件的认证逻辑区分

  • 客户端组件:必须添加 "use client" 指令,可访问浏览器API(如localStorage、useRouter),适合处理前端侧的令牌读取、页面跳转等操作,是你当前场景的首选。
  • 服务端组件:默认即为服务端组件,无法访问浏览器API,适合通过Cookie传递令牌的场景(服务端直接请求后端验证),但不适用你用localStorage存令牌的需求。

额外注意事项

  • 确保 .env.local 文件中正确配置后端地址:NEXT_PUBLIC_SERVER_URL=http://localhost:5000(替换为你的Express服务端口)
  • Express后端需正确处理 x-auth-token 请求头,验证JWT的有效性,无效时返回401状态码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 09:57:35