Next.js:实现私有路由时,如何防止在重定向之前出现未经授权的路由/页面?

Ant*_*tiz 5 reactjs higher-order-components next.js next-router

profile本质上,我为 Next.js 应用程序中的两个页面(即和)创建了一个 HOC,dashboard两个页面阻止用户在未经授权的情况下访问它们。

例子:pages/profile.js

import withAuth from "../components/AuthCheck/index";

function Profile() {
  return (
    <>
      <h1>Profile</h1>
    </>
  )
}


export default withAuth(Profile);
Run Code Online (Sandbox Code Playgroud)

我的身份验证组件/HOC:

import { useRouter } from 'next/router'
import { useUser } from '../../lib/hooks'
import { PageLoader } from '../Loader/index'

const withAuth = Component => {
  const Auth = (props) => {
    const { isError } = useUser(); //My hook which is calling /api/user see if there is a user
    const router = useRouter()


    if (isError === 'Unauthorized') {
      if (typeof window !== 'undefined' && router.pathname === '/profile' || router.pathname === 'dashboard') router.push('/login')

      return <PageLoader />
    }
    return (
      <Component {...props} />
    );

  };

  if (Component.getInitialProps) {
    Auth.getInitialProps = Component.getInitialProps;
  }

  return Auth;
};

export default withAuth;
Run Code Online (Sandbox Code Playgroud)

现在发生的情况是,如果您碰巧在浏览器地址栏中输入/profile/dashboard,在重定向之前您将看到第二个 ie flash 页面。

知道为什么会发生这种情况吗?

adr*_*ian 5

我会考虑在需要身份验证的页面上使用 getServerSideProps ,请查看getServerSideProps。它将在每个请求的页面上运行服务器端。

或者,_app.tsx__app. 更具体地说,您可以protected:true向 auth wall 后面的页面添加一个 prop(使用static props)。然后在应用程序中,您可以检查特定页面是否具有 protected===true 并在用户未经过身份验证时重定向到身份验证组件,例如:

            {pageProps.protected && !user ? (
                <LoginComponent />
            ) : (
              <Component {...pageProps} />
            )}
Run Code Online (Sandbox Code Playgroud)