Skip to content

Next.js - API Routes

Next.js allows you to build backend API endpoints directly within your project using Route Handlers. These are functions defined in route.ts (or route.js) files located within the app directory, typically under an app/api/ subdirectory.

Each route.ts file can export functions corresponding to HTTP methods (e.g., GET, POST, PUT, DELETE). These functions receive a Request object and should return a Response object (often using NextResponse helpers).

  • app/api/hello/route.ts maps to the /api/hello endpoint.
  • app/api/users/[userId]/route.ts maps to dynamic endpoints like /api/users/123.

Let’s create a basic API endpoint that returns a simple JSON message.

  1. Create the directory structure: app/api/greeting/.

  2. Inside app/api/greeting/, create a file named route.ts with the following content:

app/api/greeting/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function GET(request: NextRequest) {
// You can access query parameters from the request object
const searchParams = request.nextUrl.searchParams;
const name = searchParams.get('name') || 'World'; // Default to 'World'
const responseData = {
message: `Hello, ${name}! Welcome to the Next.js API.`
};
// Return a JSON response using NextResponse helper
return NextResponse.json(responseData);
}

This code defines an asynchronous function GET that handles GET requests to /api/greeting. It reads an optional name query parameter and returns a personalized JSON greeting.

  • File Convention: API endpoints are defined by route.ts or route.js files.
  • HTTP Methods: Export named functions matching HTTP verbs (GET, POST, PATCH, DELETE, etc.).
  • Request Object: Functions receive a Request object (standard Web API) potentially extended by NextRequest for Next.js specific helpers like nextUrl.
  • Response Object: Functions must return a Response object (standard Web API). The NextResponse helper from next/server provides convenient methods like NextResponse.json().

Run the development server if it’s not running:

npm run dev
  1. Open http://localhost:3000/api/greeting in your browser. You should see:
{"message":"Hello, World! Welcome to the Next.js API."}
  1. Now try adding a query parameter: http://localhost:3000/api/greeting?name=Alice. You should see:
{"message":"Hello, Alice! Welcome to the Next.js API."}

Route Handlers provide a robust way to build serverless API functions as part of your Next.js application, suitable for tasks like handling form submissions, interacting with databases, or integrating with third-party services.