Skip to main content

Command Palette

Search for a command to run...

NextJS API Routes

Updated
2 min read
NextJS API Routes

When you recieve a request in api route, you have to create right API.
In NextJS, you deploy the `route.ts` file beneath the app/api foler.

GET /api/users
POST /api/users
GET /api/users/[id]
PUT /api/users/[id]
DELETE /api/users/[id]

You define the method in the file.

//app/api/users/route.ts
import { NextRequest, NextResponse } from "next/server";

export function GET(request: NextRequest): NextResponse {
    // GET /api/users request
}

export function POST(request: NextRequest): NextResponse {
    // POST /api/users request
}
//app/api/users/[id]/route.ts

import { NextRequest, NextResponse } from "next/server";

export function GET(request: NextRequest, { params }: { params: { id: string } }): NextResponse {
    // GET /api/users/[id] request
}

export function PUT(request: NextRequest, { params }: { params: { id: string } }): NextResponse {
    // PUT /api/users/[id] request
}

export function DELETE(request: NextRequest, { params }: { params: { id: string } }): NextResponse {
    // DELETE /api/users/[id] request
}

As a result, you can deal with each handling.

**Query Parameter**

// ...
//e.g)GET /api/users?query=hoge 
export function GET(request: NextRequest): NextResponse {
  const params = request.nextUrl.searchParams;
  const query = params.get("query");
  // query = "hoge"
// ...

**Request Body**

// ...
// e.g)POST /api/users (request body: {"key": "hoge"}) 
export async function POST(request: NextRequest): Promise<NextResponse> {
  const params = await request.json();
  // params = {key: "hoge"}
// ...

Pass Parameter

// ...
// 例)POST /api/users (request body: {"key": "hoge"}) 
export async function POST(request: NextRequest): Promise<NextResponse> {
  const params = await request.json();
  // params = {key: "hoge"}
// ...

If multiple parameters are included, add those of types to param.

// ...
// e.g) GET /api/users/hoge/items/1
export function GET(request: NextRequest, { params }: { params: { id: string, itemId: number } }): NextResponse {
    // params.id = "hoge"
    // params.itemId = 1
}
// ...

**CORS**
If you access the API from different domain, you can defind the CORS to share the souce.

export function GET(request: NextRequest): NextResponse {
    return NextResponse.json(
        { response: "Test response." },
        {
          status: 200,  // Status code
          headers: {    // Response header
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
            "Access-Control-Allow-Headers": "Content-Type, Authorization",
          },
        },
  );
}

When defining the header in the response object, you can also define the CORS header. If there are too many endpoints, it is better to define the header in the middleware, because the header may become redundant.