Next.js 15 Tutorial - 9 - Catch all Segments
Catchall Segments in Routing
Introduction to Catchall Segments
- The discussion begins with an introduction to catchall segments, using the example of building a documentation site for a project that has multiple features and concepts.
- The goal is to create unique routes for each concept under its respective feature, leading to potentially 400 different routes if there are 20 features with 20 concepts each.
Dynamic Routing as a Solution
- Dynamic routing can significantly reduce the number of files needed by utilizing dynamic route folders with concept IDs, cutting down from 400 files to just 20.
- Further optimization can be achieved by making the feature folder dynamic as well, reducing it to only two folders: one for feature ID and one for concept ID.
Implementing Catchall Segments
- To set up catchall segments, create a
docsfolder and then another folder named with square brackets and three dots (e.g.,[...slug]) followed by creating apage.tsxfile within this slug folder.
- This setup allows any URL containing "docs" in the path to render the same page regardless of additional segments, demonstrating how catchall segments work effectively.
Accessing URL Segments in Code
- To access different URL segments in code, destructure
paramsfrom props;params.slugwill be an array of strings representing the URL parts.
- Use conditional rendering based on the length of
slugto display appropriate content depending on whether it's just a feature or includes both feature and concept.
Optional Catchall Segments
- Next.js also supports optional catchall segments. By wrapping the slug folder name in an extra pair of square brackets, you can make certain URL paths optional without triggering a 404 error.
- The choice between using a simple
page.tsxversus an optional catchall depends on whether your UI remains consistent across URLs or varies based on them.
Visualization and Conclusion