Page Routing in Next.js

By Published 3 min read

Page Routing in Next.js

Introduction:

In the dynamic world of web development, crafting a user-friendly and efficient navigation experience is crucial. Next.js, a powerful React framework, simplifies this task with its intuitive page routing system.

Understanding the Basics of Page Routing in Next.js

At the heart of Next.js lies its ability to effortlessly manage page routing. Unlike traditional server-rendered applications, Next.js support a file-based routing system, where the structure of your project’s pages directory directly corresponds to the routes in your application.

1. File-Based Routing:

The pages directory is the cornerstone of Next.js routing. Each .js or .tsx file within this directory represents a page in your application. The file name becomes the route path, facilitating an intuitive and straightforward approach to defining routes.

// Example: File-based routing in Next.js
// pages/index.js represents the route "/"
// pages/about.js represents the route "/about"
// pages/blog/[slug].js represents dynamic route "/blog/:slug"

2. Dynamic Routes:

Next.js allows dynamic routing, enabling the creation of pages with variable paths. This is achieved by using square brackets [] in the file name to denote dynamic segments.

// Example: Dynamic route in Next.js
// pages/blog/[slug].js represents dynamic route "/blog/:slug"
const BlogPost = ({ post }) => {
  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </div>
  );
};

Next.js provides a powerful Link component that simplifies client-side navigation, offering a smooth transition between pages without the need for a full-page reload.

1. Basic Usage:

The Link component is straightforward to use, accepting an href prop that specifies the destination route.

// Example: Using the Link component for client-side navigation
import Link from 'next/link';

const HomePage = () => {
  return (
    <div>
      <h1>Welcome to the Home Page!</h1>
      <Link href="/about">
        <a>About Us</a>
      </Link>
    </div>
  );
};

2. Prefetching:

Next.js provides the ability to prefetch pages, optimizing the user experience by loading the linked page in the background before it’s actually navigated to.

// Example: Prefetching with the Link component
import Link from 'next/link';

const HomePage = () => {
  return (
    <div>
      <h1>Welcome to the Home Page!</h1>
      <Link href="/about" prefetch>
        <a>About Us</a>
      </Link>
    </div>
  );
};

Advanced Routing Techniques and Best Practices

1. Nested Routes:

Next.js supports nested routes, allowing the creation of subpages within a parent page. This is achieved by organizing files in a nested directory structure within the pages folder.

// Example: Nested routes in Next.js
// pages/products/index.js represents the route "/products"
// pages/products/[id].js represents the route "/products/:id"

2. Route Parameters:

Utilize route parameters to capture dynamic segments of the URL, making it easy to handle and render content based on user input.

// Example: Route parameters in Next.js
// pages/users/[userId].js represents the route "/users/:userId"
const UserProfile = ({ user }) => {
  return (
    <div>
      <h1>{user.name}</h1>
      <p>Email: {user.email}</p>
    </div>
  );
};

Optimizing Page Routing for Performance and User Experience

1. Lazy Loading:

Employ code splitting to load only the necessary JavaScript for a specific page, enhancing performance by reducing initial page load times.

// Example: Lazy loading with dynamic imports in Next.js
const DynamicComponent = dynamic(() => import('../components/DynamicComponent'));

2. Error Handling:

Implement custom error pages to gracefully handle errors, providing a more polished user experience.

// Example: Custom error page in Next.js
// pages/_error.js represents the error page for the entire application
const CustomErrorPage = () => {
  return (
    <div>
      <h1>Oops! Something went wrong.</h1>
      <p>Please try again later.</p>
    </div>
  );
};

Conclusion

page routing in Next.js, we’ve covered the foundational aspects, advanced techniques, and best practices that empower developers to create intuitive and performant navigation experiences. As you embark on your journey with Next.js, remember that efficient page routing is not just about reaching destinations but ensuring that the journey is smooth, seamless, and tailored to the unique needs of your users. Embrace these practices, experiment with dynamic routes, and let Next.js pave the way for a delightful user experience in your web applications.

Khan Waseem is a tech lead and full-stack engineer in Bengaluru, building hospitality and SaaS software with Node.js, React and React Native. See the resume