nextjs 13提供了一种保护路由的方法吗?

9lowa7mx  于 2023-05-17  发布在  其他
关注(0)|答案(1)|浏览(115)

我有以下页面**/about,/user,/user/[id]。由于我无法访问请求页**,这给了我们slug,即(/user/[id]),我无法应用逻辑来重定向未经身份验证的用户发出的请求。所以,我的问题是nextjs 13提供了什么特定的方式来保护路由。
我尝试了next-shield,这是解决这个问题的包。但这给了我们华而不实的内容。

siotufzp

siotufzp1#

import { redirect } from 'next/navigation'可以在SSR中解决此问题
假设你有一个用于创建新博客文章的url/route,名为/new-post,你想为一个非授权用户保护这个url,并将他们重定向到其他页面。
这就是你在那种情况下要做的

const newPost = async () => {
  const loginStatus = await getLoginStatus() // get the login status
  if (!loginStatus.isLoggedIn) {
    redirect('/') // Redirect them to other pages that can access by any non-auth user
  }
  return (
    <div>
      /* Create new post page content here */
    </div>
  )
}
export default newPost

由于所有组件都是在服务器上运行的,所以在nextjs 13中,这将在服务器上准备就绪。
Refer to docs

相关问题