在 Next.js 应用程序路由器中的服务器端请求后通用重定向到登录

问题描述 投票:0回答:1

我想做一个服务器端请求并获取用户数据,这是通过 cookie 进行身份验证的。我通过

cookies
函数转发 cookie(示例中未显示)。

当身份验证失败并返回 401 时,我想重定向到

/login?redirect=[page where the request failed]

我的

/app/profile/page.tsx

import { RedirectType, redirect } from "next/navigation";

const MyProfile = async () => {
  const profile = await fetch("https://example.com/api/user/profile"); // authentificated via cookie

  if (profile.status === 401) {
    // "/profile" is hardcoded here, but it should be the current path
    redirect("/login?redirect=/profile", RedirectType.replace);
  }

  if (!profile) return <div>Loading...</div>;

  const profileData = await profile.json();

  return <div>My name is {profileData.name}</div>;
};

export default MyProfile;

我需要在几乎每个页面上执行经过身份验证的请求 - 有没有办法不在服务器端对重定向参数进行硬编码?我还有另一个概念错误吗?

谢谢!

reactjs next.js next.js13 app-router
1个回答
0
投票

您可以在 if 语句中返回一个客户端组件,该组件通过使用

usePathname
函数自动为您执行重定向,而无需每次都对重定向参数进行硬编码。

您可以调用客户端组件 RedirectComponent.tsx,它可能如下所示:

'use client'
 
import { usePathname, redirect, RedirectType } from 'next/navigation'
 
export function RedirectComponent() {
  const pathname = usePathname()
  redirect("/login?redirect=" + pathname, RedirectType.replace);

  return <></>
}

这个客户端组件不返回任何jsx,或者你可以修改它以返回任何你想要的jsx,但是只要你在服务器组件中调用或返回这个客户端组件,

usePathname
就会读取当前URL的路径名并追加它是您要重定向到的 url,在本例中为
login?redirect
+ 当前 url 路径名。

在您的代码中,您可以执行类似的操作来调用它:

import { RedirectType, redirect } from "next/navigation";
import {RedirectComponent} from "./RedirectComponent" 

const MyProfile = async () => {
  const profile = await fetch("https://example.com/api/user/profile"); // authentificated via cookie

  if (profile.status === 401) {
    // return the RedirectComponent here to automatically redirect you to the desired page
    return <RedirectComponent />
  }

  if (!profile) return <div>Loading...</div>;

  const profileData = await profile.json();

  return <div>My name is {profileData.name}</div>;
};

export default MyProfile;

为什么它必须在客户端组件中?如果我使用客户端组件,它会降低我的应用程序的性能吗?

这是来自 nextjs 文档的答案:

usePathname
有意要求使用客户端组件。重要的是要注意客户端组件并不是去优化。它们是服务器组件架构不可或缺的一部分。

© www.soinside.com 2019 - 2024. All rights reserved.