Find The Latest Tech Insights, News and Updates to Read

Routing in Next.js – A Beginner's Guide

Written by Simran Sharma | Dec 8, 2023 1:25:35 PM

Introduction

A key component of web development is routing, which enables users to move between various pages or views within an application. Popular React framework Next.js comes with a robust and adaptable routing system right out of the box.

Basics of Next.js Routing

Files in the pages directory are linked to pages in Next.js. In your application, every file in this directory instantly becomes a route. For instance, the /about route will allow access to a file called about.js located in the pages directory.

Let's build a simple, two-page Next.js application.


The two pages in this example are index.js and about.js. A client-side navigation link between these pages is made using the Next.js Link component.

Routing Types in Next.js

  • Client-Side Routing-
    By default, client-side routing is used with Next.js. The Link component doesn't reload the entire page when you navigate between pages with it. Rather, it only updates the modified portion of the page and fetches the required JavaScript.


  • Server-Side Routing-
    Server-side routing, in which some pages can be rendered on the server for improved performance, is also supported by Next.js. This can be accomplished by exporting your page components' getServerSideProps async function.

In this instance, the AboutPage component receives data as props from the server via the getServerSideProps function. Because this data fetching happens for each request, it is appropriate for dynamic data that changes often.

Conclusion

Next.js offers a smooth and adaptable routing system for server-side and client-side rendering requirements. You can give your users a seamless navigation experience by arranging your pages in the pages directory and making use of the Link component. Furthermore, the flexibility to manage dynamic content is increased by the ability to retrieve data on the server side using getServerSideProps. Next.js routing is going to be a valuable tool in your development toolbox as you create more intricate applications.