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

Next.js中getServerSideProps权限校验失败无法重定向如何解决

权限校验重定向不生效的解决方案

问题原因

  • 你的CheckToken是异步函数,调用时没有加await,校验逻辑还未执行完成getServerSideProps就已经返回了结果
  • res.redirect是Next.js API路由的专属方法,getServerSideProps场景下必须通过返回指定格式的redirect配置实现重定向,不能直接操作res对象

改造步骤

1. 修改CheckToken工具函数

调整逻辑,不直接操作res,改为返回校验结果:

// ../../../utils/CheckToken
export default async function checkToken(req) {
  try {
    // 原有校验逻辑,从req.cookies读取token校验
    // 校验通过返回true
    return true
  } catch(err) {
    // 校验失败返回false
    return false
  }
}

2. 修改页面的getServerSideProps逻辑

增加await调用,根据校验结果返回重定向配置:

// /page/post.ts
import CheckToken from '../../../utils/CheckToken';

export async function getServerSideProps(context) {
  // 加await等待异步校验完成
  const isVerified = await CheckToken(context.req);
  // 校验失败直接返回重定向配置
  if (!isVerified) {
    return {
      redirect: {
        destination: '/admin/login',
        permanent: false,
        statusCode: 401
      }
    }
  }
  // 校验通过正常返回props
  return {
    props: {
      tabledb, setting
    }
  }
}

export default function Post() {
  return <div>页面内容</div>
}

可选简化方案

如果需要多个页面复用校验逻辑,可以把校验逻辑封装成高阶函数包裹getServerSideProps,避免每个页面都写重复的判断逻辑:

// ../../../utils/withAuth
export const withAuth = (getServerSidePropsFunc) => async (context) => {
  const isVerified = await CheckToken(context.req);
  if (!isVerified) {
    return {
      redirect: {
        destination: '/admin/login',
        permanent: false,
        statusCode: 401
      }
    }
  }
  // 校验通过执行原有的getServerSideProps逻辑
  return getServerSidePropsFunc(context);
}

页面使用时直接包裹即可:

export const getServerSideProps = withAuth(async (context) => {
  return {
    props: { tabledb, setting }
  }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:15:03