javascriptreactjsnext.js

How do you put api routes in the new app folder of Next.js?


I have a test API under: pages\api\accounts\login.js. And I am learning the new app folder, which is still an experimental feature in Next.js (as of today).

Is it possible to move my login script into the app folder? I tried moving/renaming to app\api\accounts\login\pages.js, but when I do this:

async function handler(req, res) {
  console.log(res);
}
export default handler;

I use the URL: http://localhost:3000/api/accounts/login. I get:

Server Error

Error: Cannot find module for page: /api/accounts/login

I also tried moving it to: app/api/accounts/login/page.js. But I get the same error.


Solution

  • Since version 13.2, we have API Route Handlers in the app folder. They work like pages, but the file for the segment should be called route.js instead of page.js.

    For example, say you have the below file structure and code:

    enter image description here

    // app/api/route.js 👈🏽
    
    import { NextResponse } from "next/server";
    
    // To handle a GET request to /api
    export async function GET(request) {
      // Do whatever you want
      return NextResponse.json({ message: "Hello World" }, { status: 200 });
    }
    
    // To handle a POST request to /api
    export async function POST(request) {
      // Do whatever you want
      return NextResponse.json({ message: "Hello World" }, { status: 200 });
    }
    
    // Same logic to add a `PATCH`, `DELETE`...
    

    You can access /api as any API route, for example, with fetch("/api"). While going to / renders page.js.