Learn how to master Next.js 14 routing with the new src/app directory. Discover key features, dynamic routing, and nested layouts with practical examples.

Introduction

Next.js has been dominating and is arguably the leading framework for modern web development. The power to build fast and scalable applications with great developer experience is one of the best we've ever seen. Next.js 14 has a bunch of new features and enhancements, especially in routing.

One significant change is the introduction of the src/app directory, which streamlines project organization and improves managing routes.

In this article, we'll explore exactly how routing works in Next.js 14 with the src/app directory structure with example code to demonstrate and solidify your learning.

Why use the new "src/app" structure?

The biggest reason to use src/app directory is that it allows for a more organized and scalable project structure. This new directory structure is best for larger projects, as it separates application-specific logic from other code, such as components and utilities. I personally have started to use this for my own projects.

One small things to keep in mind is the file naming convention within the src/app directory which consists of a page.js file rather than index.js making it easier to define and manage routes. We'll also take a look at dynamic routing, better support for nested routes, and enhanced API route management as well.

Setting Up the "src/app" Directory

Before diving into routing, let's look at an example project setup for a Next.js 14 project using the src/app directory.

my-nextjs-app/
├── src/
│   ├── app/
│   │   ├── page.js
│   │   ├── about/
│   │   │   └── page.js
│   └── components/
│       └── Layout.js
└── package.json

You'll notice the app and components are the two main folders seperating the actual routes/pages vs the individual components of your app. This directory structure helps maintain a clean separation between different parts of the application, making it easier to manage as the project grows.

Basic Routing in Next.js 14 with "src/app" Directory

Routing in Next.js 14 is actually pretty straightforward, especially with the src/app directory. Each page.js file within the src/app directory corresponds to a route in your application. For example, a page.js file located directly inside the src/app directory represents the root route (/), while a page.js file inside an about directory represents the /about route.

Here's an example of basic routing:

// src/app/page.js > "/"
export default function Home() {
  return <h1>Welcome to the Home Page</h1>;
}

// src/app/about/page.js > "/about"
export default function About() {
  return <h1>About Us</h1>;
}

In this example, the Home component will render when users visit the root URL (/), and the About component will render when users visit /about. Next.js automatically handles these routes based on the page.js files' locations within the src/app directory.

Dynamic Routing in Next.js 14 with "src/app" Directory

Dynamic routing is a powerful feature that allows you to create routes that change based on the URL parameters. In Next.js 14, dynamic routing is easy to create within the src/app directory using square brackets to define dynamic segments in the directory names.

Here's an example of setting up a dynamic route:

// src/app/blog/[id]/page.js
import { useRouter } from 'next/router';

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

  return <h1>Blog Post {id}</h1>;
}

In this example, [id] is a dynamic segment, allowing you to capture the value from the URL and use it within the component. For instance, visiting /blog/123 would render the BlogPost component with id set to 123.

Nested Routing and Layouts in Next.js 14 with src/app Directory

Nested routing enables you to create routes that share a common layout or structure. This is particularly useful for sections of your application that require a consistent UI across multiple pages. In Next.js 14, you can achieve this by organizing your routes within the src/app directory and using a layout component.

Here's an example of implementing nested routes with shared layouts:

// src/app/dashboard/page.js
export default function Dashboard() {
  return <h1>Dashboard Home</h1>;
}

// src/app/dashboard/settings/page.js
export default function Settings() {
  return <h1>Dashboard Settings</h1>;
}

// src/components/Layout.js
export default function Layout({ children }) {
  return (
    <>
      <header>Header Content</header>
      <main>{children}</main>
      <footer>Footer Content</footer>
    </>
  );
}

In this example, the Layout component wraps around the Dashboard and Settings components, providing a consistent header and footer for both pages. By organizing your routes within the src/app directory, you can easily manage and apply shared layouts across nested routes.

API Routes in Next.js 14 with "src/app" Directory

API routes in Next.js allow you to build serverless functions that can handle requests and responses without needing a seperate server. With the src/app directory, API routes are defined similarly to regular routes, but they reside within an api directory and use the route.js naming convention.

Here's an example of creating a simple API route:

// src/app/api/hello/route.js
export async function GET(req) {
  return new Response(JSON.stringify({ message: 'Hello, Next.js 14 with src/app directory!' }), {
    status: 200,
    headers: { 'Content-Type': 'application/json' },
  });
}

In this example, the GET function handles requests to the /api/hello route and returns a JSON response. The route.js file defines the API route, and Next.js automatically handles the routing logic.

Summary

Next.js 14 introduces a more organized approach to routing with the src/app directory, making it easier to manage complex applications. By following the patterns and examples provided in this article, you can effectively leverage the new routing features to build scalable and maintainable Next.js applications. Whether you're working with basic, dynamic, or nested routes, the src/app directory offers a clear and structured way to handle your application's routing logic.

Further Reading and Resources

After reading this article you should have a solid understanding of how to use the src/app directory in Next.js 14 for routing. Thanks for reading and check out other cool tutorials down below!