Next Js File Based Routing

Harsh PatelHarsh Patel
2 min read

Next Js uses file based-routing system where each file in the directory corresponds to a route in application .

There are two types of routing Nested Routing and Dynamic Routing

Nested Routing :

To create Nested route , all you need to do is create a corresponding nested folder and any file inside it .

For eg : You want to create a route localhost:3000/profile/edit , to create this all you need to do is just create a folder name profile followed by edit folder and inside it create a file name page.js .

import React from 'react'

const page = () => {
  return (
    <div>
      This page is in edit folder
    </div>
  )
}

export default page

Dynamic routing :

Dynamic routes are created using [sno] brackets and inside that we will write “sno“ to fetch data or id which will be accessed as “route.query“. All you need to do is create a file as [sno].js inside the folder where you wanted to create . For eg : You have multiple user and you want to edit a profile of user id 6 no here you will use Dynamic routing .

Inside page.js you can write code like this :

'use client';

import { useParams } from 'next/navigation';
import React from 'react';

const Post = () => {
  const params = useParams();
  const sno = params.sno;

  return (
    <div>
      User id: {sno}
    </div>
  );
};

export default Post;

Note : By default Next js routing work for Server component as we want to work on client side and useParams , useState, useEffect .., etc are client side Hooks so it is necessary to mention 'use client';

1
Subscribe to my newsletter

Read articles from Harsh Patel directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Harsh Patel
Harsh Patel