Learn Next.js · 9/15

Route Handlers: Building Your Own API Endpoints

8 min read

Route Handlers: Building Your Own API Endpoints ⚙️

Welcome, intrepid coder! So, you've been building beautiful user interfaces with Next.js, but now you're ready to venture into the backend, to the place where the data magic happens. You're in the right place! We're about to demystify Route Handlers, your personal toolkit for building robust API endpoints right within your Next.js application.

Ever wondered how your application can "talk" to other applications or services, or how it can handle data submissions without a full page reload? That's the power of APIs, and Route Handlers are Next.js's elegant way of letting you build them.


1. Understanding route.ts: Next.js's Backend Endpoints 📂

The Problem: Your frontend needs a way to request data or send data to your server without having to reload a whole new page. Think about a "like" button on a social media post. When you click it, the count updates instantly. You don't want the entire page to refresh just for that tiny interaction.

The Solution: route.ts (or route.js) files are your dedicated backend listeners. You can create these files inside your app directory, and they will act as specific API endpoints that your frontend (or any other service) can communicate with.

Imagine you have a post office (your Next.js application). The route.ts files are like specific P.O. boxes. Each box has a unique address (the route), and you can send letters (requests) to it and receive mail (responses) from it.

How it Works:

In Next.js, you can create a route.ts file within any folder inside your app directory. The path to that folder becomes the API endpoint.

For example, if you create a file at app/api/users/route.ts, you've just created an API endpoint at /api/users. It's that simple!

Here’s a basic route.ts file:

typescript
// app/api/hello/route.ts

export async function GET(request: Request) {
  return new Response('Hello, Next.js!', {
    status: 200,
  });
}

In this tiny snippet, we've created an endpoint at /api/hello that will respond with "Hello, Next.js!" when it receives a GET request. We'll dive into what GET and Request mean in a moment.

Under the Hood: Next.js uses a file-based routing system for API routes, similar to how it handles pages. When a request hits a URL that matches a route.ts file, Next.js doesn't render a UI component. Instead, it executes the code inside that file, allowing you to run server-side logic.


2. Handling HTTP Methods: GET, POST, PUT, and DELETE 📮

HTTP methods are the verbs of the web. They tell the server what kind of action the client wants to perform. While there are several, we'll focus on the most common ones you'll use daily.

  • GET: Used to retrieve data. Think of it as asking the server, "Hey, can I get some information?"
  • POST: Used to create new data. This is like submitting a form to create a new user account.
  • PUT: Used to update existing data. Imagine editing your profile information.
  • DELETE: Used to... well, delete data. No surprises there!

The Problem: How do you tell your API endpoint to do different things based on the type of request it receives? You don't want to use the same logic for fetching data as you do for deleting it. That would be a recipe for disaster! 💥

The Solution: In your route.ts file, you can export functions with names that correspond to the HTTP methods you want to handle.

Let's see it in action:

Imagine we have an endpoint at app/api/posts/route.ts to manage blog posts.

typescript
// app/api/posts/route.ts

import { NextResponse } from 'next/server';

// To handle a GET request to /api/posts
export async function GET() {
  // In a real app, you'd fetch this from a database
  const posts = [{ id: 1, title: 'Hello Next.js' }];
  return NextResponse.json({ data: posts });
}

// To handle a POST request to /api/posts
export async function POST(request: Request) {
  const data = await request.json();
  // Here, you would typically save the data to your database
  console.log(data); // For now, we'll just log it
  return NextResponse.json({ message: 'Post created successfully' });
}

Now, if you send a GET request to /api/posts, you'll get a list of posts. If you send a POST request with some data, it will be processed (in this case, just logged to the console).

A fun fact: If you try to use an HTTP method that you haven't defined a function for (like sending a PUT request to our example above), Next.js will automatically return a 405 Method Not Allowed response. It's got your back!


3. Mastering the NextRequest and NextResponse Objects 📦

While you can use the standard Request and Response objects, Next.js provides extended versions, NextRequest and NextResponse, which give you some extra superpowers.

The Problem: A standard request can be a bit like a sealed envelope. You know it's there, but getting specific information out of it, like URL parameters or headers, can be cumbersome. Similarly, when sending a response, you want an easy way to format it, especially if you're sending JSON data.

The Solution: NextRequest and NextResponse are your specialized tools for handling these situations gracefully.

NextRequest: The Inspector 🕵️

The NextRequest object gives you easy access to all the juicy details of the incoming request.

Let's expand on our GET example to see how we can read query parameters from the URL.

typescript
// app/api/posts/route.ts
import { NextRequest, NextResponse } from 'next/server';

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;
  const query = searchParams.get('query'); // e.g., /api/posts?query=nextjs

  // In a real app, you would use this query to filter your database results
  if (query) {
    return NextResponse.json({ data: `Searching for posts about ${query}` });
  }

  return NextResponse.json({ data: 'Here are all the posts' });
}

With NextRequest, you can also easily access cookies, headers, and the request body.

NextResponse: The Messenger 🕊️

NextResponse simplifies the process of sending back a response. A very common task in API development is returning data in JSON format. NextResponse.json() makes this a breeze.

typescript
// app/api/users/route.ts
import { NextResponse } from 'next/server';

export async function GET() {
  const users = [
    { id: 1, name: 'Ada Lovelace' },
    { id: 2, name: 'Grace Hopper' },
  ];
  return NextResponse.json({ users });
}

This automatically sets the Content-Type header to application/json and stringifies your JavaScript object. Less boilerplate for you to write!


4. Building Webhooks to Integrate External Services 🎣

The Concept: Imagine you have an online store. When a customer makes a purchase through a payment provider like Stripe, you want your application to know about it immediately so you can, for example, send a confirmation email. How does Stripe tell your application about this event?

This is where webhooks come in. A webhook is essentially a POST request that an external service sends to a specific URL in your application when a particular event occurs.

The Problem: You need to create a secure and reliable endpoint in your application that can listen for these incoming webhooks from external services and then perform some action based on the data received.

The Solution: A Route Handler is the perfect tool for creating a webhook endpoint. It's a dedicated URL that can receive POST requests from services like Stripe, GitHub, or Slack.

Let's build a simple example:

Imagine we want to receive a notification from a hypothetical service whenever a new user signs up.

First, we create our endpoint:

typescript
// app/api/webhooks/user-signup/route.ts
import { NextRequest, NextResponse } from 'next/server';

export async function POST(request: NextRequest) {
  try {
    const data = await request.json();

    // It's a good practice to verify the webhook signature to ensure
    // the request is coming from the expected service.
    // Most services provide a way to do this.

    console.log('New user signed up:', data.user.name);

    // Here you could:
    // - Add the user to a mailing list
    // - Send a welcome email
    // - Update your internal analytics

    return NextResponse.json({ message: 'Webhook received successfully' }, { status: 200 });
  } catch (error) {
    return NextResponse.json({ error: 'An error occurred' }, { status: 500 });
  }
}

Now, in our hypothetical service, we would configure the webhook URL to be https://your-app-domain.com/api/webhooks/user-signup. Whenever a new user signs up on that service, it will send a POST request with the user's data to our endpoint, and our code will be executed.

Industry Practice: When working with webhooks, security is paramount. Always make sure to verify the authenticity of the incoming request. Most services that provide webhooks will also send a special signature in the request headers that you can use to verify that the request is legitimate and not from a malicious actor.

And there you have it! You've taken your first steps into building the backend of your Next.js application. With Route Handlers, you have the power to create a wide range of API endpoints, from simple data fetching to complex integrations with external services. Happy coding! 🚀


Further Reading & References

Challenge

Challenge Instructions

You are tasked with building a simple API endpoint to manage a list of products. This endpoint must be located at /api/products and handle GET, POST, and DELETE requests.

All responses must be in JSON format.

Requirements:

  1. Create the Route Handler:

    • Your code should represent the content of a route.ts file that would be placed in the app/api/products/ directory.
  2. GET Method:

    • Implement an asynchronous GET function.
    • If a category query parameter is present in the URL (e.g., /api/products?category=electronics), the handler should return only the products that match that category.
    • If no query parameter is provided, it should return the entire list of products.
  3. POST Method:

    • Implement an asynchronous POST function.
    • This function should be able to receive a new product object in the request's JSON body.
    • It should respond with a JSON object containing a success message and the product data that was received.
  4. DELETE Method:

    • Implement an asynchronous DELETE function.
    • The function should expect an id query parameter (e.g., /api/products?id=2).
    • It should respond with a JSON object containing a success message indicating which product ID was targeted for deletion.

Note: You will be working with a predefined in-memory array of products. You do not need to implement actual database logic; simply filter the existing array or process incoming data as specified.

Expected result

Your code should correctly export three asynchronous functions (GET, POST, DELETE) that handle requests as described. It should utilize the NextRequest object to access query parameters and the request body, and the NextResponse.json() method to return appropriately structured JSON data for each case.

typescript
import { NextRequest, NextResponse } from 'next/server';

// Pre-defined in-memory data. In a real application, this would come from a database.
let products = [
    { id: 1, name: 'Laptop Pro', category: 'electronics' },
    { id: 2, name: 'Ergonomic Chair', category: 'furniture' },
    { id: 3, name: 'Wireless Mouse', category: 'electronics' },
    { id: 4, name: 'Standing Desk', category: 'furniture' }
];

export async function GET(request: NextRequest) {
    const searchParams = request.nextUrl.searchParams;
    const category = searchParams.get('category');

    if (category) {
        const filteredProducts = products.filter(p => p.category.toLowerCase() === category.toLowerCase());
        return NextResponse.json(filteredProducts);
    }

    return NextResponse.json(products);
}

export async function POST(request: NextRequest) {
    const newProduct = await request.json();
    // In a real app, you would add the new product to the database.
    // Here we'll just log it and return a success response.
    console.log('Received new product:', newProduct);
    return NextResponse.json({ message: 'Product created successfully', product: newProduct }, { status: 201 });
}

export async function DELETE(request: NextRequest) {
    const searchParams = request.nextUrl.searchParams;
    const id = searchParams.get('id');

    if (!id) {
        return NextResponse.json({ message: 'Product ID is required' }, { status: 400 });
    }

    // In a real app, you would find and delete the product from the database.
    return NextResponse.json({ message: `Product with ID ${id} deleted successfully` });
}
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.