Next.js中未授权用户登录重定向时记录目标URL问题排查
问题排查与解决方案
核心错误:router.asPath调用方式错误
首先看你useAuth hook里的代码,router.asPath()是错误写法——Next.js的useRouter返回的asPath是字符串属性,不是可调用的方法。这个错误会直接抛出TypeError,中断后续逻辑,导致asPath获取失败,自然生成不了正确的redirect参数。
其他可能的问题与修复方案
修正asPath获取方式
把const asPath = router.asPath();改为:const asPath = router.asPath;避免Login页面无限重定向循环
如果你的Login页面也引入了useAuth hook,未登录状态下会触发重复重定向到Login页面,导致URL异常、页面不断跳转。需要在重定向逻辑里排除Login页面:if(user-not-logged-in && !router.asPath.includes('/some-basepath/login')){ // 后续重定向代码 }确保Login路径包含basepath
原代码中pathname: "/login"如果你的实际登录页路径是/some-basepath/login,直接写/login会跳转到根路径下的Login页面,导致URL不符合预期。修正为:router.push({ pathname: "/some-basepath/login", query: {redirect: encodedAsPath} });处理Login页面中redirect参数为undefined的情况
当用户直接访问Login页面时,router.query.redirect是undefined,直接调用decodeURIComponent会抛出错误。需要先判断参数存在再解码:useEffect(() => { if(router.isReady){ const {redirect} = router.query; if(redirect){ console.log("decoded redirect in login page = ", decodeURIComponent(redirect)); } } }, [router.isReady, router.asPath]);生成符合预期的相对路径redirect参数
如果你希望redirect参数是events%2F632dbb3f6852f而不是包含basepath的完整路径,需要从asPath中剥离basepath部分:const basePath = '/some-basepath'; const relativePath = router.asPath.replace(basePath, ''); const encodedAsPath = encodeURIComponent(relativePath);
修复后的完整useAuth代码示例
// useAuth hook中 if(user-not-logged-in && !router.asPath.includes('/some-basepath/login')){ const asPath = router.asPath; const basePath = '/some-basepath'; const relativePath = asPath.replace(basePath, ''); const encodedAsPath = encodeURIComponent(relativePath); router.push({ pathname: "/some-basepath/login", query: {redirect: encodedAsPath} }); }
内容的提问来源于stack exchange,提问作者Daniel_Kamel
相关产品推荐
相关产品推荐

