首页 > 解决方案 > Next.js + react 中的路由守卫

问题描述

我有一个关于 Next.js 和 React 的项目,它不使用任何库进行路由。我应该如何为未经身份验证的用户实施路由保护(受保护的路由)?或者如果 cookie 中没有令牌,我应该重定向它们吗?

标签: reactjsauthenticationroutesnext.js

解决方案


您可以getInitialProps通过一些适当的方式办理登机手续。评估 cookie 以决定是否重定向的逻辑。

import Router from 'next/router'

const redirectToLogin = res => {  
  if (res) {
    res.writeHead(302, {Location: '/login'})
    res.end()
    res.finished = true
  } else {
    Router.push('/login')
  }
}


class ProtectedPage extends React.Component {
  static async getInitialProps ({req, res}) {
    // get cookie from req.headers or from document.cookie in browser
    // this cookie must not contain sensitive information!
    const profile = getProfileFromCookie(req)
    if (!profile) {
      redirectToLogin(res)
    }
  }
}

看看这个示例代码https://github.com/lipp/login-with/blob/master/example/nextjs/with-profile.js#L8(我是作者)。


推荐阅读