#what does a middleware matcher actually do when combined with next-auth?

1 messages · Page 1 of 1 (latest)

regal ruin
#

in the nextjs.org/learn i see in authentication they are teaching how to use middleware to run only on select paths. but what does it do to the select paths

wheat baneBOT
#

Hi @regal ruin. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

In Next.js, the matcher in middleware is used to filter and specify the paths where the middleware should run. It allows you to target specific paths for the middleware to operate on. This is particularly useful when you want to apply certain logic, such as authentication checks, only to specific routes in your application.

You can match a single path or multiple paths using an array syntax. For example:

export const config = {
 matcher: ['/about/:path*', '/dashboard/:path*'],
}

The matcher config allows full regex, so you can match paths using negative lookaheads or character matching. For instance, you can use a negative lookahead to match all paths except specific ones:

export const config = {
 matcher: [
 '/((?!api|_next/static|_next/image|favicon.ico).*)',
 ],
}

When combined with authentication (like next-auth), the matcher can be used to protect certain routes by running authentication checks only on the specified paths. If a user tries to access a protected route, the middleware checks if the user is authenticated and can redirect unauthenticated users to a login page.

Here's an example of how to use middleware for authentication:

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
 
export function middleware(request: NextRequest) {
 const currentUser = request.cookies.get('currentUser')?.value
 
 if (currentUser) {
 return NextResponse.redirect(new URL('/dashboard', request.url))
 }
 return NextResponse.redirect(new URL('/login', request.url))
}
 
export const config = {
 matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
}
#

In this example, the middleware checks if a currentUser cookie exists. If it does, the user is redirected to the dashboard. If not, the user is redirected to the login page. The matcher is set to run this middleware on all paths except those starting with api, _next/static, _next/image, and any .png files.

Sources:


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: