DEV Community

Cover image for Next JS Routing Patterns
Shubham Tiwari
Shubham Tiwari

Posted on

8 1 1

Next JS Routing Patterns

Hello everyone today i will be discussing Next JS Routing Patterns.

Introduction:

Next.js has gained immense popularity in the React ecosystem as a powerful framework for building server-rendered React applications. One of the standout features of Next.js is its robust routing system, which allows developers to implement various routing patterns to navigate between pages. In this article, we will explore the different routing patterns available in Next.js and provide example code snippets to demonstrate their usage.

1. File-based Routing:

Next.js follows a file-based routing approach, where each page in your application is represented by a corresponding file in the pages directory. For example, creating a file named about.js inside the pages directory will automatically generate a route for /about. Let's take a look at an example:

// pages/about.js
const AboutPage = () => {
  return <h1>About Page</h1>;
};

export default AboutPage;
Enter fullscreen mode Exit fullscreen mode

2. Dynamic Routes:

Next.js provides a powerful mechanism for handling dynamic routes, allowing you to create pages with dynamic parameters. Dynamic routes are defined by enclosing a portion of the file name with square brackets ([]). Here's an example:

// pages/posts/[id].js
const PostPage = ({ id }) => {
  return <h1>Post ID: {id}</h1>;
};

export default PostPage;

export async function getServerSideProps({ query }) {
  return {
    props: {
      id: query.id,
    },
  };
}
Enter fullscreen mode Exit fullscreen mode

In the above example, the file name [id].js indicates a dynamic route where the id parameter can take different values. The getServerSideProps function is used to fetch data based on the dynamic parameter and pass it as a prop to the component.

3. Nested Routes:

Next.js supports nested routes, allowing you to create complex page hierarchies. By organizing your files into nested directories, you can create nested routes. Here's an example:

// pages/products/index.js
const ProductsPage = () => {
  return <h1>Products Page</h1>;
};

export default ProductsPage;
Enter fullscreen mode Exit fullscreen mode
// pages/products/category.js
const CategoryPage = () => {
  return <h1>Category Page</h1>;
};

export default CategoryPage;
Enter fullscreen mode Exit fullscreen mode

In this example, the file index.js inside the products directory corresponds to the route /products, while the category.js file inside the products directory corresponds to the route /products/category.

4. Custom Routes:

Next.js also allows you to define custom routes using the next/link and next/router APIs. This gives you full control over the routing mechanism and enables more complex navigation patterns. Here's an example:

import Link from 'next/link';
import { useRouter } from 'next/router';

const CustomRoutePage = () => {
  const router = useRouter();

  const handleButtonClick = () => {
    router.push('/custom-page');
  };

  return (
    <div>
      <h1>Custom Route Page</h1>
      <Link href="/about">
        <a>About</a>
      </Link>
      <button onClick={handleButtonClick}>Go to Custom Page</button>
    </div>
  );
};

export default CustomRoutePage;
Enter fullscreen mode Exit fullscreen mode

In this example, the Link component from next/link is used to create a link to the /about page. The router object from next/router is used to programmatically navigate to the /custom-page route when the button is clicked.

Conclusion:

Next.js provides a versatile and intuitive routing system that caters to various navigation needs in

THANK YOU FOR CHECKING THIS POST
You can contact me on -
Instagram - https://www.instagram.com/supremacism__shubh/
LinkedIn - https://www.linkedin.com/in/shubham-tiwari-b7544b193/
Email - shubhmtiwri00@gmail.com

^^You can help me with some donation at the link below Thank youπŸ‘‡πŸ‘‡ ^^
β˜• --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/website-components-you-should-know-25nm

https://dev.to/shubhamtiwari909/smooth-scrolling-with-js-n56

https://dev.to/shubhamtiwari909/swiperjs-3802

https://dev.to/shubhamtiwari909/custom-tabs-with-sass-and-javascript-4dej

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (5)

Collapse
 
bkpecho profile image
Bryan King Pecho β€’

Well done on explaining nested routes in Next.js. πŸ‘ It's fantastic for organizing complex page hierarchies.

Collapse
 
jon_snow789 profile image
Jon Snow β€’

Does Next.js have any routing systems other than file-based routing?
Because i like react js routing system

Can I use the same routing system in Next.js that we use in React.js?

Collapse
 
only1adams profile image
Adams Muhammed β€’

No , the new app router is also file based but it’s better than using pages router .. you can check the next js docs for more info.. you may like it

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari β€’

Sure i will check the updated docs

Collapse
 
felistus profile image
Obieze Ezeugo Felistus β€’

great piece

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more