0
0
NextjsHow-ToBeginner · 3 min read

How to Create API in App Router Next.js: Simple Guide

In Next.js App Router, create an API by adding a route.js or route.ts file inside the app/api/ folder. Export HTTP method functions like GET or POST that return a Response or NextResponse object to handle requests.
📐

Syntax

To create an API route in Next.js App Router, place a route.js file inside a folder under app/api/. Export functions named after HTTP methods like GET, POST, etc. Each function receives a Request object and returns a Response or NextResponse object.

  • GET: Handles GET requests.
  • POST: Handles POST requests.
  • Request: Incoming request data.
  • Response: What you send back.
javascript
export async function GET(request) {
  return new Response('Hello from GET API')
}

export async function POST(request) {
  const data = await request.json()
  return new Response(JSON.stringify({ message: 'Data received', data }), {
    headers: { 'Content-Type': 'application/json' }
  })
}
💻

Example

This example shows a simple API route that responds to GET requests with a greeting message and to POST requests by echoing back JSON data sent by the client.

javascript
import { NextResponse } from 'next/server'

export async function GET() {
  return NextResponse.json({ message: 'Hello from Next.js API!' })
}

export async function POST(request) {
  const data = await request.json()
  return NextResponse.json({ received: data })
}
Output
{"message":"Hello from Next.js API!"}
⚠️

Common Pitfalls

  • Not placing the route.js file inside the app/api/ folder structure.
  • Forgetting to export HTTP method functions like GET or POST.
  • Returning plain objects instead of a Response or using NextResponse.
  • Not setting proper headers like Content-Type for JSON responses.
javascript
/* Wrong: Missing export and wrong return type */
function GET() {
  return { message: 'Hello' } // This will cause an error
}

/* Right: Export and return NextResponse */
export function GET() {
  return NextResponse.json({ message: 'Hello' })
}
📊

Quick Reference

Summary tips for creating API routes in Next.js App Router:

  • Use app/api/your-route/route.js for API files.
  • Export async functions named after HTTP methods.
  • Return Response or NextResponse objects.
  • Parse request body with await request.json() for POST/PUT.
  • Set JSON headers with NextResponse.json() for convenience.

Key Takeaways

Create API routes by adding a route.js file inside app/api folders in Next.js App Router.
Export functions named after HTTP methods like GET or POST that return Response or NextResponse.
Use await request.json() to read JSON data from POST requests.
Always return a Response object with proper headers, preferably using NextResponse.json().
Keep your API files organized inside the app/api directory for automatic routing.