使用 NextJs 保护 Routes/Pages

Protect Routes/Pages with NextJs

我构建了一个简单的项目,通过使用 if 和 else 语句并为每个页面放置一个函数 withAuth() 来保护网站的 routes/pages,但我不确定如果那是使用 nextjs 保护路由的最佳方法,我注意到保护路由或页面存在延迟,例如 2-3 秒长,他们可以在重定向访问者之前看到页面内容或未注册用户到登录页面。

有没有办法摆脱它或使请求更快,以便未注册的用户不会查看页面的内容?在nextjs框架中有没有更好的方法来维护某个路由?

代码


import { useContext, useEffect } from "react";
import { AuthContext } from "@context/auth";
import Router from "next/router";

const withAuth = (Component) => {
  const Auth = (props) => {
    const { user } = useContext(AuthContext);

    useEffect(() => {
      if (!user) Router.push("/login");
    });

    return <Component {...props} />;
  };

  return Auth;
};

export default withAuth;

withAuth 的使用示例

import React from "react";
import withAuth from "./withAuth";

function sample() {
  return <div>This is a protected page</div>;
}

export default withAuth(sample);

您可以在服务器端对用户进行身份验证,如果用户已登录,则向他们显示protected route else redirect them to some other route。请参阅 this page 获取微尘信息。

getServerSideProps检查用户是否已经登录

   if (!data.username) {
        return {
            redirect: {
                destination: '/accounts/login',
                permanent: false,
            },
        }
    }

这是受保护路由页面的完整示例

export default function SomeComponent() {
    // some content
}

export async function getServerSideProps({ req }) {

    const { token } = cookie.parse(req.headers.cookie)

    const userRes = await fetch(`${URL}/api/user`, {
        method: 'GET',
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })

    const data = await userRes.json()

    // does not allow access to page if not logged in 
    if (!data.username) {
        return {
            redirect: {
                destination: '/accounts/login',
                permanent: false,
            },
        }
    }

    return {
        props: { data }
    }
}