next.jsmiddlewarematcher

How to Use Nextjs Middleware Matcher Redirect Users


I want to redirect users in my nextjs middleware matcher from "admin" to "login" page, however the redirect doesn't work, i try to match the url with the "/admin" for example "www.mydomain.com/admin" and redirect to "www.mydomain.com/login" but it doesn't work:


export function middleware(request) {
  // Middleware logic here
  const url = request.nextUrl.clone();

  // Example: Redirect if path is `/admin`
  if (url === '/admin') {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  return NextResponse.next(); // Continue to the requested page
}

// Configure the matcher to only run middleware on specific paths
export const config = {
  matcher: ['/admin', '/dashboard/:path*'], // Specify exact paths or patterns
};

I've looked online for code examples, asked a college that i work with and try to read blogs about nextjs.


Solution

  • try to match the url base on the pathname of the url rather the entire url.

      if (url.pathname === '/admin') {
        return NextResponse.redirect(new URL('/login', request.url));
      }
    

    also, i'll refer you to nextjs docs about middleware watcher to look for github code examples of nextjs middleware watcher. good luck