Next.js - Route Handlers


In this chapter, we will learn route handlers in Next.js, how to create route handlers and handle different HTTP methods in route handler.

Route Handlers in Next.js

Route Handlers in Next.js are used to create server-side API endpoints that can handle requests from the frontend or any external client. These handlers are defined using a file-based routing system and can be used to define server-side logic for fetching data, submitting forms, or implementing server-side operations.

How it Works?

  • Route Handlers in Next.js are created by adding a 'route.js' or 'route.ts' file inside the app directory.
  • Any route.js/ts file inside the app/api directory is treated as an API endpoint.
  • Any next.js component can call this API using the specified endpoint.
  • For example, if you create a route.js file at 'app/api/hello/route.js', the endpoint will be '/api/hello'.

Route Handlers can be nested anywhere inside the app directory, similar to page.js and layout.js. But there cannot be a route.js file at the same route segment level as page.js

Note: Route Handlers are specific to the App Router architecture in Next.js. If you're using the Pages Router, you should use API Routes instead.

Setting Up a Route Handler

Let's create a basic route handler that returns a JSON response. Create a file named 'route.js' inside the 'app/api/hello' directory with the following code:

// File: app/api/hello/route.js
import { NextResponse } from 'next/server';

export async function GET() {
  return NextResponse.json({ message: 'Hello from Route Handler!' });
}

Output

Now, if you visit the URL '/api/hello', you will see the following JSON response:

Next.js Route Handlers

Handling HTTP Methods

Route Handlers in Next.js can handle different HTTP methods by exporting functions named after the HTTP method they handle. Each function can process requests differently and return appropriate responses.

Example

In the following example, we create a route handler (app/api/users/route.ts) that handles different HTTP methods, and a React component (app/test-handler/page.tsx) that interacts with these endpoints.

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

export async function GET() {
  return NextResponse.json(
    { message: 'Fetching users' },
    { status: 200 }
  );
}

export async function POST(request: Request) {
  const data = await request.json();
  return NextResponse.json(
    { message: 'Creating user', data },
    { status: 201 }
  );
}

export async function PUT(request: Request) {
  const data = await request.json();
  return NextResponse.json(
    { message: 'Updating user', data },
    { status: 200 }
  );
}

export async function DELETE(request: Request) {
  const { searchParams } = new URL(request.url);
  const id = searchParams.get('id');
  return NextResponse.json(
    { message: 'Deleting user', id },
    { status: 200 }
  );
}

// File: app/test-handler/page.tsx
'use client';

import { useState } from 'react';

export default function TestHandler() {
  const [response, setResponse] = useState(null);

  const callHandler = async (method) => {
    try {
      const res = await fetch('/api/users', {
        method,
        headers: {
          'Content-Type': 'application/json',
        },
        ...(method === 'POST' || method === 'PUT' 
          ? { body: JSON.stringify({ name: 'John Doe' }) } 
          : {}),
      });

      const data = await res.json();
      setResponse(data);
    } catch (error) {
      setResponse({ error: error.message });
    }
  };

  return (
    <div>
    <h1>Test Route Handlers</h1>
    <div>
        <button onClick={() => callHandler('GET')}>GET</button>
        <button onClick={() => callHandler('POST')}>POST</button>
        <button onClick={() => callHandler('PUT')}>PUT</button>
        <button onClick={() => callHandler('DELETE')}>DELETE</button>
    </div>

    <div>
        <h2>Response:</h2>
        <pre>
        {response ? JSON.stringify(response, null, 2) : 'No response yet'}
        </pre>
    </div>
    </div>
  );
}

Output

When you visit the URL '/test-handler', you will see a React component with buttons to interact with the route handlers. Clicking on each button will call the respective handler and display the response.

Next.js Route Handlers HTTP Methods
Advertisements