episyche logo

Episyche

NextJS/Routing in NextJS/

How to Route a page in Next js?

Published on

How to Route a page in Next js?
The Next.js router allows you to do client-side route transitions between pages, similar to a single-page application. This blog shows how to route with pages in the next js. 

Introduction :

Next.js :

Next.js is a React framework. Next.js is constitutionally an excellent tool to achieve great SEO performance. building super fast static websites that behave dynamically. Next.js when building UI and UX there is flexibility. and the important great community support. To know more about relative links click here.

Next.js Routing :

Next.js has a file-system-based router and automatically treats every file with the extensions .js, .jsx, .ts, or .tsx under the pages directory as a route.

Prerequisites :

  • Next.js

Routing in a Next.js App :

There are six most common routes there in Next.js

  1. Route with pages

  2. Nested routes

  3. Dynamic routes

  4. Catch-all routes

  5. Link component navigation

  6. Programatically navigate between pages

1. Route with pages :

  • The router will automatically route files named index to the root of the directory.

  • Next.js will associate any file in this directory as a route and also route a page with a filename.

Our Scenario :


basic senerio

Steps:

Step 1: Update the index.js file

  • If you already have the Next.js project, please copy the project. In this blog, we are using a sample Next.js project code with Tailwind CSS.

nextjs_page_route_example → pages →index.js

Update the index.js in the above path, using the following snippet.

1export default function Example() { 2 return ( 3 <p className="mx-16 my-16 text-xl font-bold text-green-600 cursor-pointer"> 4 Home page 5 </p> 6 ); 7}

Step 2: Create a files

nextjs_page_route_example → pages

Create a file with a .js extension example of profile.js and about.js in the above path. As shown in the following screenshot.


folder structue

Step 3: Edit the about.js and profile.js files

nextjs_page_route_example → pages →about.js

Update the about.js in the above path, using the following snippet.

1export default function About() { 2 return ( 3 <p className="mx-16 my-16 text-xl font-bold text-green-600 cursor-pointer"> 4 About page 5 </p> 6 ); 7 }

A sample about.js file can be found in the following git repository file.

nextjs_page_route_example → pages →profile.js

Update the profile.js in the above path, using the following snippet.

1export default function Profile() { 2 return ( 3 <p className="mx-16 my-16 text-xl font-bold text-green-600 cursor-pointer"> 4 Profile page 5 </p> 6 ); 7 }

A sample profile.js file can be found in the following git repository file.

Step 4: Run your Application

Run the Next Application with the following command.

1npm run dev

After compiling your application open your browser and check the following URL:

1http://localhost:3000/

The Example UI is shown in the following screenshot.


home page image


Add the profile, to your URL using the following snippet.

1http://localhost:3000/profile

The Example UI is shown in the following screenshot.


profile page image


Add the about, to your URL using the following snippet

1http://localhost:3000/about

The Example UI is shown in the following screenshot.


about page image

2. Nested Routes:

The router supports nested files. If you create a nested folder structure, files will automatically be routed in the same way still.

Our Scenario :


nested route

Steps:

Step 1: Create the folder

nextjs_page_route_example → pages

  • create a folder with your preferred name (e.g. blog). in the above path.

nextjs_page_route_example → pages →blog

  • Create a file with a .js extension example of index.js, first.js, and second.js in the above path. As shown in the following screenshot.



folder structue 2

Step 2: Edit the pages inside the blog folder

nextjs_page_route_example → pages →blog→index.js

Update the index.js in the above path, using the following snippet.

NOTE * :

Inside any folder if set an index.js as a filename. the routers will automatically route files named with index initial.

1export default function Blog() { 2 return ( 3 <p className="mx-16 my-16 text-xl font-bold text-green-600 cursor-pointer"> 4 Blog Page 5 </p> 6 ); 7 }

A sample index.js file can be found in the following git repository file.

nextjs_page_route_example → pages →blog→first.js

Update the first.js in the above path, using the following snippet.

1export default function First() { 2 return ( 3 <p className="mx-16 my-16 text-xl font-bold text-green-600 cursor-pointer"> 4 Blog First Page 5 </p> 6 ); 7 }

A sample first.js file can be found in the following git repository file.

nextjs_page_route_example → pages →blog→second.js

Update the second.js in the above path, using the following snippet.

1export default function Second() { 2 return ( 3 <p className="mx-16 my-16 text-xl font-bold text-green-600 cursor-pointer"> 4 second Second Page 5 </p> 6 ); 7 }

A sample second.js file can be found in the following git repository file.

Step 3: Run your Application

Run the Next Application with the following command.

1npm run dev

After compiling your application open your browser and check the following URL:

1http://localhost:3000/blog

The Example UI is shown in the following screenshot.


blog page


Add the path (first), to your URL using the following snippet.

1http://localhost:3000/blog/first

The Example UI is shown in the following screenshot.


blog first page


Add the path (second), to your URL using the following snippet.

1http://localhost:3000/blog/second

The Example UI is shown in the following screenshot.


blog second page

3. Dynamic Routes:

  • Defining routes by using predefined paths is not always enough for complex applications, so we use a Dynamic route.

  • To match a dynamic segment, you can use the bracket syntax ( [ ] ). This allows you to match named parameters.

Our Scenario :


dynamic routes

Steps:

Step 1: Create the folder

nextjs_page_route_example → pages

  • Create a folder with your preferred name (e.g. product)

nextjs_page_route_example → pages →product

  • Create a file with a .js extension example of index.js and [id].js in the above path.

  • [id].js file for a dynamic route.

  • Inside the array [ ] any type of value we can send.

  • This type of route is mostly used in blogs and products like e-commerce website pages.

As shown in the following screenshot for folder structure.


folder structue 3

Step 2: Update the index.js file inside the product folder

nextjs_page_route_example → pages →product→index.js

Update the index.js in the above path, using the following snippet.

1export default function Product() { 2 return ( 3 <> 4 <div> 5 <h1 className="mx-16 mt-16 text-xl font-bold text-green-600 cursor-pointer"> 6 Product List 7 </h1> 8 <div className="text-gray-600 mx-16 mt-4"> 9 <p> Product 1 </p> 10 <p> Product 2 </p> 11 <p> Product 3 </p> 12 <p> Product 4 </p> 13 </div> 14 </div> 15 </> 16 ); 17}

A sample index.js file can be found in the following git repository file.

Step 3: Get query parameters from a URL

nextjs_page_route_example → pages →product→[id].js

  • Update the [id].js in the above path,

  • we are using useRouter hook, so we have imported the same here. using the following snippet.

1import { useRouter } from "next/router";

Easily we get the query param using the UseRouter() method. If you want to access the router object inside any function component in your app, you can use the useRouter hook. using the following snippet.

1export default function ProductDetails() { 2 3 const router = useRouter(); 4 const {id} = router.query 5 6 return ( 7 <> 8 <p className="mx-16 my-16 text-xl font-bold text-green-600 cursor-pointer"> 9 Product Product Details {id} 10 </p> 11 </> 12 ); 13 }

A sample [id].js file can be found in the following git repository file.

Step 4: Run your Application

Run the Next Application with the following command.

1npm run dev

After compiling your application open your browser and check the following URL:

1http://localhost:3000/product

The Example UI is shown in the following screenshot.


product list page


Add the path (product4), to your URL using the following snippet.

1http://localhost:3000/product/product4

In this UI example, we get query param ( product4 ) from the URL and display the param value.

NOTE * :

This example related to blogs pages, displaying the multiple blogs in a webpage when click particular blog it to be display brief notes about that blog.

The Example UI is shown in the following screenshot.


product page

4. Catch-all routes and optional catch-all routes:

The catch-all routes ( […param].js) are different from optional catch-all routes ( [[…param]].js). In optional catch-all routes, the route without the parameter will also get a match, but in catch-all routes, the route without the parameter will not match, In the given below example we’ll explain briefly.

Our Scenario :


catch all routes

Steps:

Step 1: Create a Catch-all route folder

nextjs_page_route_example → pages

  • Create a folder with your preferred name (e.g. docs). in the above path.

nextjs_page_route_example → pages →docs

  • Create a file with a .js extension example of […params].js in the above path.

  • This type of route is mostly used in documentation website pages for multi-nested routes.

As shown in the following screenshot for folder structure.


folder structue 4

Step 2: Update the […params].js file inside the docs folder

nextjs_page_route_example → pages →docs→ […params].js

Update the […params].js in the above path. On this page, we are using useRouter hook, so we have imported the same here. using the following snippet.

1import { useRouter } from "next/router";
  • Easily we get the query param value using the UseRouter() method.

  • If you want to access the router object inside any function component in your app, you can use the useRouter hook. using the following snippet

1 const router = useRouter(); 2 const { params =[] } = router.query; 3 console.log(params);
  • After getting a param value from the URL. apply condition with params for displaying the param value. using the following snippet.

1 if (params.length === 2) { 2 return ( 3 <h1 className="mx-16 mt-16 text-xl font-bold text-green-600 cursor-pointer"> 4 the docs of head {params[0]} and concept {params[1]} 5 </h1> 6 ); 7 } else if (params.length === 1) { 8 return ( 9 <h1 className="mx-16 mt-16 text-xl font-bold text-green-600 cursor-pointer"> 10 the docs of head {params[0]} 11 </h1> 12 ); 13 } 14 return ( 15 <> 16 <div> 17 <h1 className="mx-16 mt-16 text-xl font-bold text-green-600 cursor-pointer"> 18 Docs Home page 19 </h1> 20 </div> 21 </> 22 );

As shown in the following screenshot.


params routing


Step 3: Run your Application

Run the Next Application with the following command.

1npm run dev

After compiling your application open your browser and check the following URL :

1http://localhost:3000/docs

The Example UI is shown in the following screenshot.


404 page


The above screenshot was a 404 error because the route without the parameter ( localhost:3000/docs/ ) will not match so, throw an error.

So, this file changed catch-all routes to optional catch-all routes. file name [...params].js to [[…params]].js.


params structure


A sample […params].js file can be found in the following git repository file.

And check your browser. The example UI is shown in the following screenshot.


docs home page


Add the path (1), to your URL using the following snippet.

1http://localhost:3000/docs/1

As shown in the following screenshot.


doc head 1


Add the path (5), to your URL using the following snippet.

1http://localhost:3000/docs/1/5

In this URL we can send multiple params. As shown in the following screenshot.


doc head 1 and 5

  • Link is one of the components in Next.js

  • It is used to create links between pages in a Next.js app

  • <Link> allows you to do client-side navigation and accepts props that give you better control over the navigation behavior.

Steps:

Step 1: Update the index.js in the pages folder

nextjs_page_route_example → pages →index.js

  • Update the index.js in the above path.

  • For this example, we are using the Link from next. so we have imported the same here. using the following snippet.

1import Link from "next/link";

After importing the Link component from next, use the Link to navigate between pages. using the following snippet.

1 return ( 2 <> 3 <div className="my-8"> 4 <Link href="/"> 5 <a className="mx-16 my-16 text-xl font-bold text-green-600 cursor-pointer">Home</a> 6 </Link> 7 <Link href="/about"> 8 <a className="mx-16 my-16 text-xl font-bold text-green-600 cursor-pointer">about</a> 9 </Link> 10 <Link href="/product"> 11 <a className="mx-16 my-16 text-xl font-bold text-green-600 cursor-pointer">product</a> 12 </Link> 13 </div> 14 </> 15 );

As shown in the following screenshot.


indesjs


A sample index.js file can be found in the following git repository file.

Step 2: Update the index.js in the product folder

nextjs_page_route_example → pages →product→index.js

  • Update the index.js in the above path.

  • For this example, we are using the Link from next. so we have imported the same here. using the following snippet.

1import Link from "next/link";

After importing the Link component from next, use the Link to navigate between pages. using the following snippet.

1 return ( 2 <> 3 <div> 4 <Link href="/"> 5 <a className="mx-4" >Home</a> 6 </Link> 7 <h1 className="mx-16 mt-16 text-xl font-bold text-green-600 cursor-pointer"> 8 Product List 9 </h1> 10 <div className="text-gray-600 mx-16 mt-4"> 11 <Link href="/product/1"> 12 <a className="mx-4">Product 1</a> 13 </Link> 14 <Link href="/product/2"> 15 <a className="mx-4">Product 2</a> 16 </Link> 17 <Link href="/product/3"> 18 <a className="mx-4">Product 3</a> 19 </Link> 20 <Link href="/product/4"> 21 <a className="mx-4">Product 4</a> 22 </Link> 23 </div> 24 </div> 25 </> 26 );

As shown in the following screenshot.


product index


A sample index.js file can be found in the following git repository file.

Step 3: Update the [id].js in the product folder

nextjs_page_route_example → pages →product→[id].js

  • Update the [id].js in the above path.

  • For this example, we are using the Link from next. so we have imported the same here. using the following snippet.

1import Link from "next/link";

After importing the Link component from next, use the Link to navigate between pages. using the following snippet.

1 return ( 2 <> 3 <Link href="/"> 4 <a>Home</a> 5 </Link> 6 7 <p className="mx-16 my-16 text-xl font-bold text-green-600 cursor-pointer"> 8 Product Product Details {id} 9 </p> 10 </> 11 );

As shown in the following screenshot.


product single


A sample [id].js file can be found in the following git repository file.

Step 3: Run your Application

Run the Next Application with the following command.

1npm run dev

After compiling your application open your browser and check the following URL :

1http://localhost:3000/

The Example UI is shown in the following screenshot. and click to about.


link page


After clicking about, the page navigates to the about page. shown in the following screenshot.


about page image2


Please come to the back and click on Product. The Example UI is shown in the following screenshot.


link page 2


  • After clicking Product, the page navigates to the product page.

  • shown in the following screenshot. Click to Product 1



list of product

  • After clicking Product 1, the page navigate to [ id ].js page.

  • As shown in the following screenshot. and click the Home link.



home links

  • After clicking Home link the page navigate to the Home page.

  • As shown in the following screenshot.



screenshot

6. Navigating Programmatically

  • In the above routes, all are set in the Link component from next js.

  • In Programmatically navigation, click a particular button or text the page navigates to a custom URL.

Our Scenario :


navigate programattically

Steps:

Step 1: Create a button in the index.js file

nextjs_page_route_example → pages →index.js

  • Update the index.js in the above path.

  • we are using useRouter hook, so we have imported the same here. using the following snippet.

1import { useRouter } from "next/router";

If you want to access the router object inside any function component in your app, you can use the useRouter hook. using the following snippet.

1var router = useRouter();

Add the button with a function. using the following snippet.

1<button className="border text-white font-bold p-1 bg-green-700 mx-12 rounded" onClick={handleClick}> 2 place order 3</button>
1 function handleClick(){ 2 router.push("/product") 3 }

As shown in the following screenshot.

A sampleindex.js file can be found in the following git repository file.

Step 3: Run your Application

Run the Next Application with the following command.

1npm run dev

After compiling your application open your browser and check the following URL :

1http://localhost:3000/

The Example UI is shown in the following screenshot. and click to place order button.

After clicking the place order button, the page navigates to /product page. As shown in the following screenshot.

A Sample GitHub repo, with all the required configurations, is given below.

Comments