Building a Multi-Page Application with Next.js

Building a Multi-Page Application with Next.js

Learn how to leverage the powerful features of Next.js to build a multi-page application with ease.

Introduction

Next.js is an incredibly versatile React framework, known for its powerful features like server-side rendering (SSR), static site generation (SSG), and easy routing. It allows developers to build full-stack, dynamic applications with ease, all while benefiting from fast loading times and enhanced SEO capabilities.

One of the common use cases for Next.js is creating a multi-page application (MPA). In an MPA, each page is a separate entity, and navigating between pages results in loading new content. Unlike single-page applications (SPA), where the content is dynamically updated within the same page, MPAs provide distinct, separate views.

In this blog, we will guide you through building a multi-page application with Next.js. We will cover how to create different pages, manage dynamic routes, use layouts to maintain consistency across pages, and implement a navigation system.


Main Content

1. Understanding Routing in Next.js

One of the simplest yet powerful features of Next.js is its routing system. In a Next.js application, pages are created by adding files to the pages directory. Each file automatically becomes a route. For example:

/pages
  /index.js
  /about.js
  /contact.js
  • /pages/index.js: This is your homepage, accessible at the root of your site (e.g., https://your-site.com/).

  • /pages/about.js: This file represents the about page, accessible via https://your-site.com/about.

  • /pages/contact.js: The contact page, accessible via https://your-site.com/contact.

Each of these pages can export a React component, and Next.js automatically handles the routing for you. No additional configuration is required.

2. Dynamic Routes for Multi-Page Applications

Sometimes, you might want to create routes that are not static but depend on data passed through the URL. This is where dynamic routing in Next.js comes into play. Dynamic routes are created by using square brackets ([]) in file names within the pages directory.

For instance, let’s say you want to create a blog where each post is accessed via a unique URL. You would create a dynamic route like this:

/pages
  /posts/[id].js

In the file /posts/[id].js, the id is a dynamic parameter that will be passed through the URL. For example, if a user accesses /posts/123, Next.js will render the page for the post with the ID of 123.

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

const Post = () => {
  const router = useRouter()
  const { id } = router.query

  return <h1>Post ID: {id}</h1>
}

export default Post

Explanation:

  • useRouter hook: This hook is provided by Next.js to access the current route's parameters.

  • router.query.id: This retrieves the id parameter from the URL.

Now, when you visit /posts/123, the page will display Post ID: 123.

3. Creating Layouts for Consistent UI

In a multi-page application, you often need to ensure that certain elements (like headers, footers, or sidebars) remain consistent across all pages. Instead of repeating these elements on each page, you can create a layout component and use it across all your pages.

Let’s create a basic layout component:

// components/Layout.js
const Layout = ({ children }) => {
  return (
    <div>
      <header>
        <h1>My Multi-Page App</h1>
        <nav>
          <a href="/">Home</a> | <a href="/about">About</a> | <a href="/contact">Contact</a>
        </nav>
      </header>
      <main>{children}</main>
      <footer>
        <p>Footer content here</p>
      </footer>
    </div>
  )
}

export default Layout

Now, you can use this Layout component in your pages:

// pages/index.js
import Layout from '../components/Layout'

const Home = () => {
  return (
    <Layout>
      <h2>Welcome to the homepage!</h2>
    </Layout>
  )
}

export default Home

Explanation:

  • Layout component: This component wraps the main structure of your page, including a header, navigation, footer, and the dynamic content (children).

  • children: This prop is where the unique content of each page (e.g., the home, about, or contact page content) will be inserted.

This ensures that all pages in the app share the same structure while allowing for unique content.

4. Adding Navigation to Your MPA

To navigate between pages in a multi-page application, Next.js provides a special Link component from the next/link package. This component optimizes navigation by pre-fetching linked pages, improving the performance of your app.

Here’s how you can add navigation between the home, about, and contact pages:

// components/Nav.js
import Link from 'next/link'

const Nav = () => {
  return (
    <nav>
      <Link href="/">
        <a>Home</a>
      </Link>
      <Link href="/about">
        <a>About</a>
      </Link>
      <Link href="/contact">
        <a>Contact</a>
      </Link>
    </nav>
  )
}

export default Nav

Then, use the Nav component in your layout:

// components/Layout.js
import Nav from './Nav'

const Layout = ({ children }) => {
  return (
    <div>
      <header>
        <h1>My Multi-Page App</h1>
        <Nav />
      </header>
      <main>{children}</main>
      <footer>
        <p>Footer content here</p>
      </footer>
    </div>
  )
}

export default Layout

Explanation:

  • <Link> component: This component is used for navigation in Next.js. It allows you to link to other pages without causing full-page reloads, improving the user experience.

  • href: The URL that you want to link to.


Examples/Case Studies

Case Study 1: Blog Application

In a blog application, you can leverage Next.js’s dynamic routes to create individual pages for each post. Using layouts ensures consistency across the blog, while the Link component handles navigation between posts.

Case Study 2: E-commerce Store

For an e-commerce site, you can use dynamic routes to display individual product pages, categories, and a shopping cart. The layout component can be reused to display product information, and the navigation will allow users to seamlessly browse products and manage their cart.


Tips/Best Practices

  • Use Static Generation for Better Performance: In Next.js, you can pre-render static pages at build time using getStaticProps and getStaticPaths. This is especially useful for blogs or product pages that don’t change often.

  • Organize Pages and Components: Structure your project by separating pages, components, and utilities. This keeps your codebase clean and maintainable.

  • Optimize Navigation: Use next/link for client-side navigation and pre-fetching to improve page load times.

  • Use Dynamic Imports for Large Components: For large components or sections of a page, consider using dynamic imports to split the code and reduce initial loading times.

  • Handle Error Pages: Make sure to create a custom error page (e.g., pages/404.js) to improve user experience when users visit non-existent routes.


Conclusion

Building a multi-page application with Next.js is both simple and efficient. Next.js’s routing system, support for dynamic pages, and flexible layout components make it the ideal framework for creating scalable and maintainable web applications. By combining these features, you can build fast, SEO-friendly, and user-friendly MPAs with ease.

Start by organizing your pages in the pages directory, create reusable layout components, and implement navigation using the Link component. With these tools, you can create a smooth, efficient, and scalable multi-page application.

Ready to build your own multi-page application with Next.js? Get started today by setting up your project and creating dynamic pages that will enhance your web app.


References/Resources


*Image is designed by Freepik.