How to catch all routes in Next.js ?
In this article, we will learn how we can catch all routes in our NextJS project. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally. Routing defines the way in which the client requests are handled by the application endpoints.
Catch all routes: We can catch all paths in NextJs using catch-all routes. For this, we have to add three dots inside the square brackets in the name of the file as shown below:
Create NextJS Application: You can create a new NextJs project using the below command:
npx create-next-app gfg
After creating your project folder(i.e. gfg), move to it by using the following command.
Project Structure: It will look like this.
Explanation: In the above code, we are using the useRouter hook to access the router object. Router object contains the data about the current route such as pathname, query, asPath, etc. So first, we are importing useRouter in our file and after that, we are creating a new variable to store the value of the router object. Then we are displaying the value of the asPath property of the router object.
Step to Run Application: Run the application using the following command from the root directory of the project.
npm run dev