Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Next.js Tutorial
  • Next.js Components
  • Next.js Functions
  • Next.js Deployment
  • Next.js Projects
  • Next.js Routing
  • Next.js Styles
  • Next.js Server-Side Rendering
  • Next.js Environment Variables
  • Next.js Middleware
  • Next.js Typescript
  • Next.js Image Optimization
  • Next.js Data Fetching
Open In App
Next Article:
Next.js Optional catch all routes
Next article icon

Next.js Optional catch all routes

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 routes

Optional 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]].js

Steps 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 gfg

Project 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:


Next Article
Next.js Optional catch all routes

I

imranalam21510
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • ReactJS
  • Next.js

Similar Reads

    How to Catch All Routes in Next.js ?
    To catch all routes in Next.js, you create a dynamic route file using the catch-all segments syntax. This allows you to handle various routes dynamically, enhancing routing flexibility and application structure.Catch all routesTo catch all routes in next js, We willCreate a file named [...gfg].js in
    2 min read
    Next JS Dynamic API Routes
    Next.js dynamic API routes allow you to create flexible endpoints that can handle various parameters, enabling powerful and versatile server-side functionalities within your application.Prerequisites:JavaScript and React JS basicsFamiliar with Next JSRestful API's conceptDynamic API RoutesDynamic AP
    2 min read
    Next JS 13 App Router
    Routing refers to the process of determining how an application responds to a client request to a particular endpoint or URL. When a user clicks a link, enters a URL in the browser, or performs some action that changes the current URL, the routing mechanism decides which content or component to disp
    5 min read
    How to use Next.js API Routes?
    Next.js API Routes are a feature of Next.js that allows you to create server-side logic and APIs within your Next.js application. These API routes are implemented using files in the `pages/api` directory of your Next.js project. When you deploy your Next.js application, these API routes are automati
    8 min read
    Next.js Intercepting Routes
    Next.js is the most widely used React framework. With each new major release, the Next.js team is adding amazing features to the framework. Here, We will deep dive into a feature called Intercepting Routes which was added in a recent release to render modal on the same page with a unique URL. Interc
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences