DEV Community

Cover image for Next.js ~API Routes~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on Edited on

Next.js ~API Routes~

With API Routes(or Route Handlers) of Next.js, you can build the API endpoint in the application directly without an extra server.

There are two ways: App Router and Pages Router. Each of them has a different implementation.


1 . Implementation for App Router

You have to create the api folder under the app/ directory, and place router.ts in the api folder. This method is recommended in Next.js

Structure of directories

text

app/
└── api/
    └── user/
        └── route.ts  #This is the URL: /api/user 
Enter fullscreen mode Exit fullscreen mode

Example (app/api/user/route.ts)

HTTP methods such as GET and POST can be exported as the name of a function.

typescript

import { NextResponse } from 'next/server';

// GET request
export async function GET() {
  const data = { message: 'Hello from App Router!' };
  return NextResponse.json(data);
}

// POST request
export async function POST(request: Request) {
  const body = await request.json();
  return NextResponse.json({ received: body }, { status: 201 });
}
Enter fullscreen mode Exit fullscreen mode

2 . Implementation for Pages Rpouter

You have to place a file under pages/api/ directory. This is the conventional method.

Structure of directories

text

pages/
└── api/
    └── user.ts  # /api/user
Enter fullscreen mode Exit fullscreen mode

Top comments (0)