如何在 Nextjs 应用程序路由器中保护路由(最佳方式)

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

请注意,它不是一个完整的 Nextjs 堆栈项目,因为后端是在 Nodejs 中构建的。我想知道什么是最好和最佳的方式来保护我的路线免受未经授权的访问。我看到了 Nextjs 文档并阅读了我可以使用的中间件文件,但这对我来说似乎有点令人困惑。我有身份验证页面 ('/Login' 、 '/Signup') 和仪表板 ('/') 和单个帖子 ('/post/:id') 。如果用户未登录,我想保护仪表板和单个帖子路由,即他应该被重定向到登录。

javascript next.js nextjs14
1个回答
0
投票

这是一个使用中间件检查每个传入请求是否通过身份验证的简单示例。


import { auth } from "@/auth"; // your authentication to backend
import { NextRequest, NextResponse } from 'next/server';

// Specify protected and public routes
const publicRoutes = ['/login', '/signup'];

export default async function middleware(req: NextRequest) {
  // Determine if the current route is public or protected
  const path = req.nextUrl.pathname; //incoming request
  const isPublicRoute = publicRoutes.includes(path);

  const session = await auth();

  // Redirect to /login if the user is not authenticated and the route is protected
  if (!isPublicRoute && session === null) {
    return NextResponse.redirect(new URL('/login', req.nextUrl));
  }

  // No redirection needed for public routes or authenticated users on protected routes
  return NextResponse.next();
}

// Routes Middleware should not run on
export const config = {
  matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
};

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