Hammad - BlogDefining Routes

blog-image

How to Define Routes in Next.js 14

Next.js is a popular React framework that simplifies server-side rendering and the building of static web applications. One of the core features of Next.js is its flexible routing system, which allows developers to create custom routes and define how they handle incoming requests.

With the release of Next.js 14, the routing system has been improved and enhanced with several new features and changes. One of the most notable additions is the support for App Router, which is a new way of defining routes in the app directory, instead of the pages directory. App Router allows developers to create more complex and dynamic routes, and also use Route Handlers, which are functions that are executed when users access site routes.

In this article, we will take a closer look at App Router in Next.js 14, the benefits it offers, and how you can implement it in a Next.js application.

What is App Router in Next.js 14?

App Router is a new feature of Next.js 14 that allows developers to define routes in the app directory, instead of the pages directory. The app directory is a special directory that contains files and folders that are related to the application logic, such as layouts, components, hooks, and utilities. The pages directory is still used to define the page components that render the UI for each route.

App Router enables developers to create more complex and dynamic routes, such as nested routes, dynamic routes, catch-all segments, and optional segments. It also allows developers to use Route Handlers, which are functions that are exported from a route.js file as middleware that intercepts incoming requests and returns the required data.

App Router follows the same file-system-based routing mechanism as the pages directory, where URL paths in the browser are determined by files and folders in the codebase. However, there are some differences and conventions that developers need to follow when using App Router. Let’s discuss and understand them.

How to Create a Route with App Router in Next.js 14?

To create a route with App Router in Next.js 14, you need to follow these steps:

  1. Create a file with the name page.js inside the app directory. The file name should match the route path that you want to handle. For example, if you want to handle the /posts route, you should create a file named app/posts/page.js.
  2. Define a React component in the file that renders the UI for the route. The component should accept a props object as a parameter. The props object will contain the data that is returned from the Route Handler or the getServerSideProps or getStaticProps functions. For example, if you want to create a page component for the /posts route, you can write something like this:

// app/posts/page.js
import React from 'react'

function PostsPage(props) {
// render the UI for the posts page using the props data
}

export default PostsPage

  1. Optionally, you can also create a file with the name layout.js inside the same folder as the page.js file. The layout.js file should export a React component that wraps the page component and provides a common layout for the route. For example, if you want to create a layout component for the /posts route, you can write something like this:

// app/posts/layout.js
import React from 'react'
import Header from '../components/Header'
import Footer from '../components/Footer'

function PostsLayout({ children }) {
return (
<div> <Header /> {children} <Footer /> </div>
)
}

export default PostsLayout

  1. Optionally, you can also create a file with the name route.js inside the same folder as the page.js file. The route.js file should export a Route Handler function that handles the incoming request for the route and returns the required data. For example, if you want to create a Route Handler for the /posts route, you can write something like this:

// app/posts/route.js
import { getPosts } from '../lib/api'

export async function get(req, res) {
// get the posts data from the API
const posts = await getPosts()
// send the posts data as JSON
res.json(posts)
}

By following these conventions, we have successfully created a route with App Router. Open your browser and navigate to localhost:3000/posts to see the posts page.

How to Use Dynamic Routes with App Router in Next.js 14?

Dynamic routes are routes that can match any URL path that follows a certain pattern. They are useful for creating pages that depend on user input or external data, such as blog posts, products, profiles, etc. To create a dynamic route with App Router in Next.js 14, you need to follow these steps:

  1. Create a folder with the name [param] inside the app directory. The folder name should be enclosed in square brackets and should match the name of the dynamic parameter that you want to use. For example, if you want to create a dynamic route for individual posts, such as /posts/1 or /posts/2, you should create a folder named app/posts/[id].
  2. Create a file with the name page.js inside the [param] folder. The file should export a React component that renders the UI for the dynamic route. The component should accept a props object as a parameter. The props object will contain the data that is returned from the Route Handler or the getServerSideProps or getStaticProps functions. It will also contain a params object that has the value of the dynamic parameter. For example, if you want to create a page component for the individual posts route, you can write something like this:

// app/posts/[id]/page.js
import React from 'react'

function PostPage(props) {
// get the post id from the params object
const { id } = props.params
// render the UI for the post page using the props data
}

export default PostPage

  1. Optionally, you can also create a file with the name layout.js inside the [param] folder. The layout.js file should export a React component that wraps the page component and provides a common layout for the dynamic route. For example, if you want to create a layout component for the individual posts route, you can write something like this:

// app/posts/[id]/layout.js
import React from 'react'
import Header from '../../components/Header'
import Footer from '../../components/Footer'

function PostLayout({ children }) {
return (
<div> <Header /> {children} <Footer /> </div>
)
}

export default PostLayout

  1. Optionally, you can also create a file with the name route.js inside the [param] folder. The route.js file should export a Route Handler function that handles the incoming request for the dynamic route and returns the required data. The function should accept a req and res parameter, which are the request and response objects from Node.js. The req object will have a params property that has the value of the dynamic parameter. For example, if you want to create a Route Handler for the individual posts route, you can write something like this:

// app/posts/[id]/route.js
import { getPostById } from '../../lib/api'

export async function get(req, res) {
// get the post id from the req.params object
const { id } = req.params
// get the post data by id from the API
const post = await getPostById(id)
// send the post data as JSON
res.json(post)
}

By following these conventions, we have successfully created a dynamic route with App Router. Open your browser and navigate to localhost:3000/posts/1 or localhost:3000/posts/2 to see the individual posts pages.

What are the Benefits of App Router in Next.js 14?

App Router in Next.js 14 offers several benefits, such as:

Conclusion

App Router is a powerful and convenient feature of Next.js 14 that allows developers to define routes in the app directory, instead of the pages directory. The app directory is a special directory that contains files and folders that are related to the application logic, such as layouts, components, hooks, and utilities. The pages directory is still used to define the page components that render the UI for each route.

App Router enables developers to create more complex and dynamic routes, such as nested routes, dynamic routes, catch-all segments, and optional segments. It also allows developers to use Route Handlers, which are functions that are executed when users access site routes and return the required data.

In this article, we have learned what App Router is, how to create and use it, and what benefits it offers. We hope that this article has helped you to understand and appreciate App Router in Next.js 14, and that you will use it in your next web project.

For more information: nextjs.org