Skip to content

Routing in Next.js Static and Dynamic.

Posted on:September 10, 2023 at 10:10 AM

Next.js is a powerful framework that simplifies the process of building web applications. If you’ve worked with React.js, you’re probably familiar with the concept of routing. However, when it comes to Next.js, routing is even simpler. All you need to do is create a folder or file, and that’s it. Unlike React, where you have to install a separate library for routing, Next.js provides an easy and straightforward approach. Let’s dive into it.

Table of contents

Open Table of contents

Static Routing

Static routing in Next.js 13 is as simple as creating a new file in the ‘pages’ directory. The path to the file becomes the URL path, and the exported React component in the file becomes the page’s content. For example if you want about page. all you have to do is to create folder called about inside folder you name your file page.js, it will be accessible at /about.

For example:

pages/
├─ about
├─── page.js

this will automatically generate the following routes in your Next.js application: ‘/about’ (from ‘page.js’).

Route Grouping

In Next.js, you can group routes by creating subfolders within the ‘pages’ directory. However, there are some nuances to be aware of:

Dynamic Routing

In static route we know the route we want to go but what if we don’t the name of route. it could come from the database or blog post slug. it’s dynamic data so we need to use dynamic route to access.

Dynamic routing allows you to create routes that correspond to patterns, rather than fixed paths. In Next.js 13, you define dynamic routes by naming a page with square brackets. For example, ‘pages/post/[id].js’ matches ‘/post/1’, ‘/post/abc’, and so on.

Here’s an example of how you might use dynamic routing:

// pages/post/[id].js
import { useRouter } from 'next/router'

export default function Post() {
  const router = useRouter()
  const { id } = router.query

  return <p>Post: {id}</p>
}

In this example, the page will display the text “Post: ” followed by the value of id.

Conclusion

In conclusion, whether you choose static or dynamic routing in Next.js depends on your specific needs and the structure of your application. Both methods provide an easy and efficient way to manage routes in your Next.js application.

Thanks for Reading 🙏🏻