next.js 如何将客户端“身份验证”系统迁移到新的应用路由器?

g0czyy6m  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(91)

由于应用程序路由器变得稳定,我决定从旧的页面文件夹迁移。
在应用程序路由器之前,一种常见的方法是使用getserverversideprops函数来确定用户是否登录。如果他不是,那么他被重定向到登录页面(反之亦然)。
如何在新的应用程序路由器中实现相同的结果?
有人能举个例子吗?

guykilcj

guykilcj1#

您也可以在服务器组件中执行相同的操作。您现在可以创建一个异步服务器组件来复制相同的行为,而不是使用服务器端props。

import "server-only";
import { redirect } from next/navigation;

interface Props extends React.PropsWithChildren {}

// will render children if authenticated and 
// redirect to login otherwise.
async function AuthRedirect({ children }: Props): Promise<JSX.Element> {
  const auth = await getAuth();
  if (!auth) redirect("/login");
  return <>{children}</>;
}

export default AuthRedirect;
export type { Props as AuthRedirectProps };

在上面的示例中,您可以将这个组件导入到您只想向经过身份验证的用户显示的任何页面中,并使用它 Package 页面内容。

重要提示

server-only软件包需要单独安装,如果您尝试在客户端使用服务器组件,它会用来抛出错误。

相关问题