Next.js is a popular React framework that simplifies server-side rendering and the building of static web applications. One of core features in Next.js is its flexible routing system, which allows developers to create custom routes and define how they handle incoming requests.
With the recent release of v13.2, Next.js has introduced several new features and changes to routes that make it even more powerful and easy to use. Whether you’re a seasoned Next.js developer or just getting started, understanding Route Handlers is essential to building fast, scalable, and maintainable web applications.
In this article, we’ll take a closer look at the newly improved Route Handlers in Next.js, the added perks, its similarity to Remix’s routing system, and how you can implement them in a Next.js application.
Jump ahead:
- What are Route Handlers in Next.js?
- Improvements in v13.2
- Similarities between Next.js Route Handling and the Remix routing system
- Getting started with the Next.js Route Handler
- Dynamic and static generated functions in Next.js Router Handlers
What are Route Handlers in Next.js?
Route Handlers are functions executed when users access site routes. They’re responsible for handling incoming HTTP requests for the defined URLs or routes to produce the required data. In essence, when a user visits a particular page or URL in a Next.js application, the corresponding Route Handler handles the request created by the user and returns the appropriate response thereby rendering desired content.
Route Handlers in Next.js can come in a couple forms:
- Functions exported from a page file as middleware that intercept incoming requests
- Custom server-side functions for handling requests and responses for specified routes in the web application
What can we do with Route Handlers?
With Route Handlers, we can create dynamic routes, which consist of a URL that contains variable parameters that we can use to generate dynamic content. Here, the variables can be appended to the URL based on the user’s site actions and can help to carry information to different routes in the application.
Overall, Route Handlers are an essential part of Next.js, allowing us to define custom routing logic and handle incoming requests in a flexible and efficient manner.
Improvements in v13.2
Routing is essential for web applications because it handles what content is made available on different web URLs/routes. In earlier versions of Next.js, when you created a new application, you would get a pages/api
directory within the application file structure. API routes were defined in this pages/api
directory. This was due to the fact that there was no system in place to handle routes within the app
directory in earlier versions of Next.
The new Next.js v13.2 release has added a Route Handler feature to Next applications and also added support for dynamic route imports. This addition means that pages can be loaded on demand, ultimately improving performance and reducing initial load times.
Creating a new Next.js application with the latest version now places the api
directory within the app
folder. These Route Handlers provide inbuilt functions for handling various kinds of requests and responses, allowing developers to specify custom behavior for specific routes. This allows for greater flexibility and control over how routes are handled, including redirecting to other pages and providing data responses.
With this new feature, we can create API request handlers inside the app
directory by exporting functions that match to HTTP request methods such as GET
, POST
, PUT
, etc. This is typically done with the following steps:
- A
route.ts
(orroute.js
if you’re not using TypeScript) is created within theapp
directory - This file will export an asynchronous function named with your desired HTTP request:
GET
,HEAD
,POST
,PUT
,DELETE
, etc.
N.B., Route Handlers in Next.js v13.2 are meant to be a replacement for API Routes; as such, they are no longer available in the
pages
directory. Instead, we can now use the file created in the steps above.
Similarities between Next.js route handling and the Remix routing system
The Remix routing system is built on top of React Router, so it bears some similarities to Next.js route handling patterns. Below is a list of similarities between how these two frameworks handle routing in applications:
- Defining and managing routes: Remix and Next.js v13.2 allow developers to define and manage routes for their web applications using TypeScript/JavaScript files that contain handler functions
- Route-based code splitting: Remix and Next.js v13.2 use route-based code splitting, which means that each route loads only the code necessary for that particular page. This practice significantly boosts site performance because it reduces the amount of code that must be loaded on the initial execution of the application
- Nested route support: Both frameworks have support for nested routes, allowing pages and components to be created within folders in such a way that the components created with a nested folder structure within the directory will be treated as nested routes of a defined parent route
Getting started with the Next.js Route Handler
In this section, we’ll demonstrate how to use the Next’s new route handling features. To get started, we’ll first need to create a new Next.js application. Do this with the following commands in your CLI:
npx [email protected] router-handling
For this tutorial, we’ll be using the following configurations during the setup process:
When the installation process is completed, we will have a Next.js project folder "router-handler"
using Next.js v13.2. In this folder, we have the following in the app
directory:
┣ 📂app ┃ ┣ 📂api ┃ ┃ ┗ 📂hello ┃ ┃ ┃ ┗ 📜route.js ┃ ┣ 📜favicon.ico ┃ ┣ 📜globals.css ┃ ┣ 📜layout.js ┃ ┣ 📜page.js ┃ ┗ 📜page.module.css
Here, we have the api
directory in the app
folder, and an example API route hello
is generated by default.
Creating a new API route
To create a new API route, create a folder in the app/api
directory with the name of our route. Within it, create a route.js
function that exports our HTTP request; in this case, we’ll create a route called "test"
. To do this, create a new test
folder in the app/api
directory, create a route.js
file, and add the following code to it:
// In this file, we can define any type of request as follows: // export async function GET(Request) {} // export async function HEAD(Request) {} // export async function POST(Request) {} // export async function PUT(Request) {} // export async function DELETE(Request) {} // A simple GET Example export async function GET(Request) { return new Response("This is a new API route"); }
Here, we have a GET
request that returns a simple text response. To access this API route, start the application server with the npm run dev command
in the CLI. Then, open up the localhost
server in the browser and append the API URL: /api/test
. For example, if the localhost
runs on port 3000
, we will have localhost:3000/api/test
. This will produce a result similar to the image below:
Building nested and dynamic routes
Next.js v13.2 also supports dynamic API routes. To create a dynamic API route, in the app/api
folder, create a username
folder for the route and define a dynamic route. For the purpose of this example, we will create a dynamic route [user]
in the app/api/username
directory. Then, inside the [user]
route, create a route.js
file with the following:
export async function GET(request, { params }) { // we will use params to access the data passed to the dynamic route const user = params.user; return new Response(`Welcome to my Next application, user: ${user}`); }
To access the API, open up http://localhost:3000/api/username/[your username]
in place of the username. Keep in mind that you can enter any string — for example, http://localhost:3000/api/username/eric
. This will produce the following result:
Creating nested APIs in Next.js is quite simple. To create a nested route, first define the parent API route in app/api
. Any subfolders added to the created parent route
are treated as nested routes rather than separate routes.
In the example above, we created a username
route and nested a dynamic route [user]
within it. In app/api/username
, we can define the parent route in a route.js
, as shown below:
export async function GET(request) { // username parent route return new Response("This is my parent route"); }
We can access the parent route via the URL localhost:3000/api/username
, like so:
Accessing the defined nested route http://localhost:3000/api/username/[your username]
will produce the earlier result.
Creating secured routes
To create secured routes in Next.js, middleware functions are required to authenticate and authorize the requests made to the route before allowing access to it. Defining a secured route usually follows a pretty standard pattern.
First, create a middleware function that examines the incoming request headers, cookies, query parameters, etc. and determines whether the user is authorized to access the requested resources. In the event that the user is not authorized, the app will return a 401
or 403
status.
We can define the route we’d like to secure using the middleware function. Below, we illustrate an example of secured routes made with NextAuth.js. To install the package, enter the following in the CLI:
npm install next-auth
With that installed, we can create a secured API route in the api
directory. First, we will define the authentication option with its provider. Create a folder auth
, and in this folder, add a new file […nextauth].js
. This file will contain the options for whatever authentication measure you choose.
For example, using Google authentication providers, the option will be defined as follows:
import NextAuth from 'next-auth'; import GoogleProvider from "next-auth/providers/google"; const authOptions = { providers: [ GoogleProvider({ clientId: process.env.CLIENT_ID, clientSecret: process.env.CLIENT_SECRET, authorization: { params: { prompt: "consent", access_type: "offline", response_type: "code" } } }) ], // Add your session configuration here session: { jwt: true, } }; export default NextAuth(authOptions);
For the secured route, create a new folder session
in the api
directory and add the route to be secured as a route.js
file. In session/route.js
, add the following:
import { getServerSession } from "next-auth/next"; import authOptions from "../auth/[...nextauth]"; export async function GET(Request) { const session = await getServerSession(authOptions); if (session) { // Signed in console.log("Session", JSON.stringify(session, null, 2)); return new Response("Welcome authenticated user", { status: 200, }); } else { // Not Signed in return new Response("Unauthorized access detected", { status: 401, }); } }
Now, attempting to access the /api/sesssion
route will display the following result:
Here, the app returns the response Unauthorized access detected
with status code 401
.
Dynamic and static generated functions in Next.js Router Handlers
In addition to routing functions, Next 13.2 also provides features to use server-side dynamic functions such as cookies, headers, and redirects. Dynamic functions are executed on the server side when defined routes are accessed.
This is best suited for handling tasks such as data upload or requesting and accessing a database. By defining router handler functions as dynamic, developers can ensure better performance because the function is only executed when the specified route is accessed, thereby preventing unnecessary server-side processing.
On the other hand, static Route Handlers allow the developer to generate static content for specified routes, which is created at build time. This is particularly useful for frequently accessed routes containing content that won’t often change and, as such, can be pre-rendered ahead of time.
With static functions, developers can reduce the load on server-side processing for dynamic functions required to generate content for a defined route. Proper use of dynamic and server-side functions together make for a more performant application. With dynamic and static functions explained, let’s take a look at examples under both categories: the static Route Handler and dynamic Route Handler.
Static Route Handler
For this example, we will use the GitHub search user API. Make the following changes to route.js
in the app/api/username
directory:
import { NextResponse } from 'next/server'; export async function GET() { const res = await fetch( "https://api.github.com/search/users?q=richard&per_page=3" ); const data = await res.json(); return NextResponse.json(data); }
In the code block above, we are performing a GET
request to the GitHub search API and returning a response containing three users with the name "richard"
. Navigating to the username
route will produce results similar to the image below:
Dynamic Route Handler
For dynamic server-side functions, we can use cookies, redirects, and headers. To use redirects, we need to add an import
for the redirect
dependency and specify the redirect URL. For example, we can create a redirect URL in the username
route, as shown below:
import { redirect } from "next/navigation"; const name = "John Doe"; export async function GET(Request) { redirect(`http://localhost:3000/api/username/${name}`); }
Here, we are redirecting users to the dynamic [user]
route and passing along a name
variable. Redirects can also be used with external URLs to other webpages.
With server-side functions, we can also specify route headers. This is particularly useful in cases where you need to specify different headers for different routes, especially if the routes require a different authorization bearer or authentication token, as shown below:
// Import for the headers dependency import { headers } from 'next/headers'; export async function GET(Request) { const useHeader = headers(Request); const header = useHeader.get('content-type'); return new Response('We are using the content-type header!', { status: 200, headers: { 'content-type': header } }); }
In the code block above, we are using the headers
function from next/headers
to get the headers from the incoming request
object passed to the Route Handler. Then, we use the GET
method from the Route Handler to extract the value of the content-type
parameter.
Finally, we create a new response with a status of 200
and set the headers to the value of the Request
header. One major improvement to the route headers in Next 13.2 is that they can now be executed dynamically based on the responses of incoming requests or the data being fetched.
Conclusion
Congratulations on making it to the end of this guide on Next.js Route Handlers. In this post, we discussed how the new Route Handlers in v13.2 compare to route handling in older versions, how this new paradigm compares to the Remix routing system, and demonstrated how you can get started creating API routes in the new Next.js v13.2. Happy coding!