使用 NextJS 和 Auth0 时如何添加共享布局?

How to add a shared layout when using NextJS and Auth0?

我已经按照 Next 文档设置了我的布局,效果很好。但是,NextJS Auth0 SDK 有一个 withPageAuthRequired 包装打破了这种模式。

我使用的模式来自这些docs。例如,这是一个页面组件:

function Page(): ReactElement {
  return <DashboardLayout>"Code Detail Page"</DashboardLayout>
}

Page.getLayout = function getLayout(page: ReactElement) {
  return <DashboardLayout>{page}</DashboardLayout>
}

export default withPageAuthRequired(Page)

然后在我的 _app.tsx:

type NextPageWithLayout = NextPage & {
  getLayout?: (page: ReactElement) => ReactNode
}

type AppPropsWithLayout = AppProps & {
  Component: NextPageWithLayout
}

function MyApp({ Component, pageProps }: AppPropsWithLayout) {
  const getLayout = Component.getLayout || ((page) => page)

  return (
    <UserProvider>
        {getLayout(<Component {...pageProps} />)}
    </UserProvider>
  )
}

export default MyApp

我遇到的问题是我的布局不再被拉动,我假设这是因为 Auth0 包装器。

如果我执行以下操作,我可以渲染布局,但我需要在 AuthWrapper.getLayout 赋值之前添加一个 // @ts-ignore

const AuthWrapper = withPageAuthRequired(Page)

AuthWrapper.getLayout = function getLayout(page: ReactElement) {
  return <DashboardLayout>{page}</DashboardLayout>
}
export default AuthWrapper

是否有另一种方法可以使用这种模式的布局,而不需要将 // @ts-ignore 添加到我的所有经过身份验证的页面?

我认为您使用 withPageAuthRequired 有误。它用于包装getServerSideProps,而不是页面。

If you wrap your getServerSideProps with WithPageAuthRequired your props object will be augmented with the user property, which will be the user's Claims

export const getServerSideProps = withPageAuthRequired({
  getServerSideProps: async ({ req, res }) => {
    const auth0User = getSession(req, res);
    ... add logic here

    return {
      props: {
        myProp,
      },
    };
  },
});