oliviarizona
oliviarizona

Reputation: 59

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.

Upvotes: 2

Views: 55

Answers (1)

Turing Vang
Turing Vang

Reputation: 73

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

Upvotes: 1

Related Questions