Search⌘ K
AI Features

Building API Endpoints with Route Handlers

Explore how to build API endpoints in Next.js using Route Handlers to manage GET, POST, PUT, and DELETE requests. Learn to handle raw JSON data, dynamic route parameters, URL query filtering, and implement caching strategies for efficient data responses.

In the previous chapters, we used page.js to render UI and Server Actions to handle mutations. But what if we need to expose raw data to the outside world, rather than HTML?

Because page.js is strictly designed to return visual components, it cannot function as a standard API endpoint. For cases where we need to support a mobile app, receive a webhook, or let third parties fetch our data, we need a standard HTTP interface.

In this lesson, we will learn about Route Handlers (route.js). These allow us to bypass React rendering entirely and return raw JSON, XML, or files directly to the client.

What are Route Handlers?

Think of Route Handlers as dedicated functions that run on the server in response to specific network requests. They typically live inside the app/api directory, and we use a route.js or route.ts file to define the API logic for a specific endpoint. This convention-based routing should feel familiar; it’s the same principle we use for creating pages.

Handling collection endpoints

Let’s start by creating a simple endpoint that fetches all users from an array to simulate an in-memory database.

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <main>{children}</main>
      </body>
    </html>
  );
}
Fetching all users with a GET request

Explanation

  • Line 2: We import NextResponse, which extends the standard Web API Response object and includes helpful Next.js-specific utilities. For example, automatic JSON serialization with NextResponse.json() and built-in support for advanced caching and revalidation.

  • Lines 5–8: We initialize a users array to act as our simple in-memory database.

  • Line 11: ...