Catch-All Routes in Next.js allow dynamic URL matching with flexible path parameters, empowering your app’s routing system.
Key Features
- Dynamic Parameters: Access route wildcard segments through the … rest parameter.
- Matching Order: Definition order determines the route precedence.
- Fallback behavior: Optionally configure fallback settings.
Configuration
Next.js routing file (pages/foo/[…bar].js):
- Root Catch-All: Load for any unmatched path or
/fooroute without further subpaths.
export default function CatchAll() {
// Logic for Root Catch-All
}
- Nested Catch-Alls: Triggered when the root path is accessed along with subdirectories.
export default function NestedCatchAll() {
// Logic for Nested Catch-All
}
- Fallback Pages: Ideal for error handling or awaiting dynamic data.
export async function getServerSideProps() {
// Data-fetching logic
return { props: { data } };
}
export default function Fallback({ data }) {
return <div>{data}</div>;
}
Fallback Modes
Specify fallback behavior in the getStaticPaths method:
- True: Generates paths at build time and handles missing routes as fallbacks (SSG-only).
- False: Precisely predefines page paths during build (no fallback).
- ‘blocking’: Handles fallbacks via server at run-time (SSR or SSG).