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

如何在urql的errorExchange中适配新版next/router实现未认证跳转

解决方案1:直接使用Next.js内置的Router单例(适配Pages Router)

你不需要使用useRouter钩子,Next.js的next/router包默认导出的单例Router可以在非React组件环境直接调用,和Ben原教程的写法逻辑完全一致,修改代码如下:

  1. 修改导入语句
// 替换原有 import { useRouter } from 'next/router'
import Router from 'next/router'
  1. 直接在errorExchange中调用单例方法
const errorExchange: Exchange = ({ forward }) => (ops$) => {
  return pipe(
    forward(ops$),
    tap(({ error }) => {
      if (error?.message.includes("not authenticated")) {
        Router.replace("/auth/login");
      }
    })
  );
};

该方法完全符合语法规则,不需要修改其他业务代码即可直接生效。

解决方案2:自定义事件通信(通用兼容所有路由模式,适配App Router升级需求)

如果后续要升级到Next.js App Router,或者不想依赖全局Router单例,可以用事件监听实现解耦:

  1. 在errorExchange中触发自定义事件
const errorExchange: Exchange = ({ forward }) => (ops$) => {
  return pipe(
    forward(ops$),
    tap(({ error }) => {
      if (error?.message.includes("not authenticated")) {
        // 触发全局自定义事件
        window.dispatchEvent(new CustomEvent('authRequired'))
      }
    })
  );
};
  1. 在根组件pages/_app.tsx中监听事件并调用路由方法
import { useRouter } from 'next/router'
import { useEffect } from 'react'

function MyApp({ Component, pageProps }) {
  const router = useRouter()
  useEffect(() => {
    const handleAuthRequired = () => {
      router.replace('/auth/login')
    }
    // 绑定监听事件
    window.addEventListener('authRequired', handleAuthRequired)
    // 组件卸载时移除监听
    return () => window.removeEventListener('authRequired', handleAuthRequired)
  }, [router])
  return <Component {...pageProps} />
}

export default MyApp

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:57:01