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

如何在Next.js中全局实现令牌过期移除LocalStorage并渲染登出页?

解决方案:全局实现令牌过期检查与处理

问题根源

你仅在首页单独编写了useEffect检查逻辑,其他页面未引入这段代码,因此只有首页加载时会执行令牌判断。要让所有页面生效,需把逻辑放到全局入口组件中。

实现步骤

  1. 封装复用的权限检查Hook
    将令牌检查、过期判断、移除与跳转逻辑封装成自定义Hook,便于维护:

    import { useEffect } from 'react';
    import { useRouter } from 'next/router';
    
    const useAuthCheck = () => {
      const router = useRouter();
    
      useEffect(() => {
        // 确保仅在客户端执行(Next.js服务端渲染时无localStorage)
        if (typeof window === 'undefined') return;
    
        const token = localStorage.getItem('key');
        // 令牌不存在或无效的情况
        if (!token) {
          localStorage.removeItem('key');
          // 避免重复跳转登录页
          if (router.pathname !== '/login') {
            router.push('/login');
          }
          return;
        }
    
        // 解析JWT令牌判断过期时间(若使用JWT格式)
        try {
          // 拆分JWT的payload部分并解码
          const payload = JSON.parse(atob(token.split('.')[1]));
          const currentTimestamp = Date.now() / 1000;
          // 检查令牌是否过期
          if (payload.exp < currentTimestamp) {
            localStorage.removeItem('key');
            if (router.pathname !== '/login') {
              router.push('/login');
            }
          }
        } catch (err) {
          // 令牌格式错误,直接视为无效
          localStorage.removeItem('key');
          if (router.pathname !== '/login') {
            router.push('/login');
          }
        }
      }, [router]);
    };
    
    export default useAuthCheck;
    
  2. 在全局入口组件中使用Hook
    Next.js的_app.tsx(或_app.jsx)是所有页面的统一入口,在这里引入Hook,所有页面加载时都会自动执行检查:

    import type { AppProps } from 'next/app';
    import useAuthCheck from '../hooks/useAuthCheck';
    
    export default function App({ Component, pageProps }: AppProps) {
      // 全局执行权限检查
      useAuthCheck();
      return <Component {...pageProps} />;
    }
    

额外说明

  • 若你使用的不是JWT令牌,只需把过期判断逻辑替换为对应令牌的校验方式即可。
  • 添加typeof window === 'undefined'判断,是为了避免Next.js服务端渲染时访问localStorage报错。
  • 跳转前判断当前路径,防止进入无限跳转循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 02:42:19