Next.js - API Routes
Next.js - API Routes with Route Handlers
Section titled “Next.js - API Routes with Route Handlers”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.tsmaps to the/api/helloendpoint.app/api/users/[userId]/route.tsmaps to dynamic endpoints like/api/users/123.
Creating a Simple API Endpoint
Section titled “Creating a Simple API Endpoint”Let’s create a basic API endpoint that returns a simple JSON message.
-
Create the directory structure:
app/api/greeting/. -
Inside
app/api/greeting/, create a file namedroute.tswith the following content:
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.
Key Concepts
Section titled “Key Concepts”- File Convention: API endpoints are defined by
route.tsorroute.jsfiles. - HTTP Methods: Export named functions matching HTTP verbs (
GET,POST,PATCH,DELETE, etc.). - Request Object: Functions receive a
Requestobject (standard Web API) potentially extended byNextRequestfor Next.js specific helpers likenextUrl. - Response Object: Functions must return a
Responseobject (standard Web API). TheNextResponsehelper fromnext/serverprovides convenient methods likeNextResponse.json().
Start Development Server
Section titled “Start Development Server”Run the development server if it’s not running:
npm run devVerify Output
Section titled “Verify Output”- Open
http://localhost:3000/api/greetingin your browser. You should see:
{"message":"Hello, World! Welcome to the Next.js API."}- 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.