<- Back

what is dynamic routes in NextJS

Normally when you request the page/api endpoint from nextjs server, nextjs looks into pages directory and finds the file and sends the response. That's called as static route. e.g. If file is located at pages/tech/tesla, nextjs will go and check if "tech" folder is available and then in that folder "tesla" file is available or not.

In addition to static routes, NextJS is also able to handle dynamic routes as well. Normally If we try to access file at pages/tech/iphone, and if that file does not exist in tech directory, nextjs will throw error saying file not found.

But with dynamic route, nextjs can process such requests. To create dynamic route, you will need to create a file with specific naming convention e.g. pages/tech/[blog].js

Now if you send the request to get files like

  • /tech/xyz (e.g. https://www.softpost.org/tech/xyz)
  • /tech/abc (e.g. https://www.softpost.org/tech/abc)
  • /tech/pqr (e.g. https://www.softpost.org/tech/pqr)

all these files will be handled by dynamic route at pages/tech/[blog].js

what is catch all route

One limitation of dynamic route specified above is that it can not handle nested paths in routes. e.g. If you send request to get "/tech/aws/iam", it will throw 404 error. That's when catch all route feature comes into picture.

Catch all route is an extension of dynamic route. You can create catch all route using below syntax. pages/tech/[...blog].js

Please note 3 dots here. The main benefit of catch all route is that it can handle nested folders and files as well. So if you request a page at pages/tech/bac/xyz, pages/tech/c/xyz/ki etc. All thesee routes will be handled by pages/tech/[...blog].js

Errors associated with catch all route

If you create 2 dynamic routes under same folder, you will get error saying "You cannot use different slug names for the same dynamic path"

e.g. pages/tech/[blog].js and pages/tech/[news].js

Here we have created 2 dynamic paths under same directory "tech" NextJS does not allow this. Instead of this, you can use catch all route to handle all dynamic routes.

Example

Here is an example showing how you can use catch all route in nextJS.


export const getServerSideProps = async (context) => {
  const path = require("path");
  const { routepath } = context.params;

  //Create a catch all route at tech/[[...routepath]]
  //If you try to access tech/xyz/abc, below statement will print array like ['xyz','abc']
  //If you try to access tech/pqr, below statement will print array like ['pqr']

  console.log("routepath ", routepath);

 return {
    props: {
      message:"This is catch all routes demo",
    },
  };

}

Web development and Automation testing

solutions delivered!!