0
0
NextJSframework~5 mins

Matching paths with config in NextJS

Choose your learning style9 modes available
Introduction

Matching paths with config helps your app decide what to show based on the URL. It makes navigation smooth and organized.

You want to show different pages for different URLs in your Next.js app.
You need to protect some pages and only allow access if the path matches certain rules.
You want to load specific data or components depending on the URL path.
You want to create a menu that highlights the current page based on the path.
Syntax
NextJS
export const config = {
  matcher: ['/path1', '/path2/:id', '/dashboard/:section*']
};

The matcher array lists paths or patterns to match.

Use :param for dynamic parts and * for wildcards.

Examples
This matches exactly '/about' and '/contact' paths.
NextJS
export const config = {
  matcher: ['/about', '/contact']
};
This matches any blog post path like '/blog/my-post'.
NextJS
export const config = {
  matcher: ['/blog/:slug']
};
This matches '/dashboard' and any deeper paths like '/dashboard/settings/profile'.
NextJS
export const config = {
  matcher: ['/dashboard/:section*']
};
Sample Program

This component uses the config matcher to handle '/profile/:id' and '/settings' paths. It shows different text based on the current URL path.

NextJS
import { usePathname } from 'next/navigation';

export const config = {
  matcher: ['/profile/:id', '/settings']
};

export default function Page() {
  const pathname = usePathname();

  if (pathname.startsWith('/profile/')) {
    return <p>Profile page for user ID: {pathname.split('/')[2]}</p>;
  }

  if (pathname === '/settings') {
    return <p>Settings page</p>;
  }

  return <p>Home page</p>;
}
OutputSuccess
Important Notes

Matchers help Next.js know which paths your code should handle specially.

Dynamic segments like :id let you capture parts of the URL.

Use usePathname() hook to get the current path inside components.

Summary

Matchers define which URL paths your code should respond to.

Use dynamic segments and wildcards to match flexible paths.

Matching paths helps build clear, organized navigation in Next.js apps.