From 2becf45f33aea49d5f67002e08607468b7de51b7 Mon Sep 17 00:00:00 2001 From: Alejandro Bailo <59607668+alejandrobailo@users.noreply.github.com> Date: Wed, 16 Jul 2025 12:39:05 +0200 Subject: [PATCH] feat: Next.js middleware improved (#8295) --- ui/middleware.ts | 32 +++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/ui/middleware.ts b/ui/middleware.ts index a8a754c879..b3411760e9 100644 --- a/ui/middleware.ts +++ b/ui/middleware.ts @@ -2,15 +2,24 @@ import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/auth.config"; +const publicRoutes = [ + "/sign-in", + "/sign-up", + // In Cloud uncomment the following lines: + // "/reset-password", + // "/email-verification", + // "/set-password", +]; + +const isPublicRoute = (pathname: string): boolean => { + return publicRoutes.some((route) => pathname.startsWith(route)); +}; + export default auth((req: NextRequest & { auth: any }) => { const { pathname } = req.nextUrl; const user = req.auth?.user; - if ( - !user && - !pathname.includes("/sign-in") && - !pathname.includes("/sign-up") - ) { + if (!user && !isPublicRoute(pathname)) { return NextResponse.redirect(new URL("/sign-in", req.url)); } @@ -26,6 +35,15 @@ export default auth((req: NextRequest & { auth: any }) => { }); export const config = { - // https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher - matcher: ["/((?!api|_next/static|_next/image|.*\\.png$).*)"], + matcher: [ + /* + * Match all request paths except for the ones starting with: + * - api (API routes) + * - _next/static (static files) + * - _next/image (image optimization files) + * - favicon.ico (favicon file) + * - *.png, *.jpg, *.jpeg, *.svg, *.ico (image files) + */ + "/((?!api|_next/static|_next/image|favicon.ico|.*\\.(?:png|jpg|jpeg|svg|ico|css|js)$).*)", + ], };