0
0
NextjsHow-ToBeginner · 4 min read

How to Create POST API in Next.js: Simple Guide

In Next.js, create a POST API by adding a server route file under app/api/your-route/route.js and export an async POST function that handles the request. Use await request.json() to read the POST data and return a response with NextResponse.json().
📐

Syntax

To create a POST API in Next.js (App Router), export an async POST function from a route.js file inside app/api/your-endpoint/. The function receives a Request object and returns a Response.

  • POST(request): Handles POST requests.
  • request.json(): Reads JSON body from the request.
  • NextResponse.json(data): Sends JSON response.
javascript
import { NextResponse } from 'next/server';

export async function POST(request) {
  const data = await request.json();
  // process data
  return NextResponse.json({ message: 'Success', received: data });
}
💻

Example

This example shows a simple POST API that receives JSON data with a name field and responds with a greeting message.

javascript
import { NextResponse } from 'next/server';

export async function POST(request) {
  try {
    const { name } = await request.json();
    if (!name) {
      return NextResponse.json({ error: 'Name is required' }, { status: 400 });
    }
    return NextResponse.json({ message: `Hello, ${name}!` });
  } catch {
    return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
  }
}
Output
POST /api/greet with body {"name":"Alice"} returns {"message":"Hello, Alice!"}
⚠️

Common Pitfalls

Common mistakes when creating POST APIs in Next.js include:

  • Not exporting the POST function correctly.
  • Forgetting to parse the JSON body with await request.json().
  • Returning plain objects instead of using NextResponse.json().
  • Not handling errors or missing fields in the request body.

Always validate input and return proper HTTP status codes.

javascript
/* Wrong way: Missing export or wrong function name */
export async function post(request) {
  const data = await request.json();
  return { message: 'Hi' };
}

/* Right way: Correct export and response */
import { NextResponse } from 'next/server';

export async function POST(request) {
  const data = await request.json();
  return NextResponse.json({ message: 'Hi' });
}
📊

Quick Reference

  • Place API route files under app/api/your-route/route.js.
  • Export async POST function to handle POST requests.
  • Use await request.json() to read JSON body.
  • Return response with NextResponse.json().
  • Validate input and handle errors gracefully.

Key Takeaways

Create POST API by exporting async POST function in app/api/your-route/route.js.
Use await request.json() to parse JSON data from the request body.
Return JSON responses with NextResponse.json() for proper HTTP handling.
Validate input data and handle errors to avoid bad requests.
Follow Next.js App Router conventions for API routes placement and naming.