Last Updated : 29 Jul, 2024
Optional catch-all routes in Next.js provide a way to define dynamic routes that can match multiple path segments, allowing more flexibility in routing.
Optional catch-all routesOptional catch-all routes in Next.js extend the concept of catch-all routes by allowing you to handle routes with a variable number of segments, including the option of no segments at all.
We can make catch-all routes optional in NextJS using optional catch-all routes. For this, we have to add three dots inside the double square brackets in the name of the file. For example:-
./pages/[[...file_name]].jsSteps to Create NextJS Application
Step 1: You can create a new NextJs project using the below command:
npx create-next-app gfg
Step 2: After creating your project folder(i.e. gfg), move to it by using the following command.
cd gfgProject Structure:
Example: Now let's create a new dynamic route to optionally catch all the paths. For this, we are going to create a new javascript file inside a new route folder in our pages directory with the name [[...gfg]].js. After that add the below content in that file.
JavaScript
// Filename - pages/[[...gfg]].js
// Importing useRouter()
import { useRouter } from "next/router";
function Gfg() {
// Initializing useRouter()
const router = useRouter();
return <h1>Path :- {router.asPath} </h1>;
}
export default Gfg;
Here we are using use router to get the value of the current path and then we are displaying the current Pathname.
Step to Run Application: Run the application using the following command from the root directory of the project.
npm run dev
Output:
How is catch-all routes different from optional catch-all routes ?In optional catch-all routes the route without the parameter will also get match ( in the above example '/route' is also matching) but in catch-all routes, the route without the parameter will not match.
Lets change the above optional catch all routes file [[.gfg]].js to catch all routes file [...gfg].js with the below content.
JavaScript
// Filename - [...gfg].js
// Importing useRouter()
import { useRouter } from "next/router";
function Gfg() {
// Initializing useRouter()
const router = useRouter();
return <h1>Path :- {router.asPath} </h1>;
}
export default Gfg;
Now this will not match the path '/route'.
Step to Run Application: Run the application using the following command from the root directory of the project.
npm run dev
Output:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4