skip to Main Content

I have a test API under: pagesapiaccountslogin.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 appapiaccountsloginpages.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.

3

Answers


  1. Since version v13.2, we have Route Handlers in the app folder. It works like pages, but the file for the segment should be called route.js or route.ts. For example:

    enter image description here

    // app/list-items/route.ts 👈🏽
    
    export async function GET(request) {
      // Do whatever you want
      return new Response('Hello, Next.js!', {
        status: 200,
      });
    }
    

    And at this point, you can access it as any API route, for example, with fetch("/list-items"). While going to / renders page.tsx.

    Login or Signup to reply.
  2. This has changed as of last week.

    The new app folder requires a route.ts under the pathing.

    For instance if you want app/api/accounts/login, your file pathing should be

    app/api/accounts/login/route.ts

    route.ts will be inside of your login folder and contains all of the logic for your api endpoint. For example

    APP Api Example

    Each folder is an endpoint, and requires a route.ts. To the best of my knowledge this is how it works, but I am still learning the new app directory.

    Login or Signup to reply.
  3. Api routes in app directory is quite simple, actually, but it’s still beta. Using your example, you would have to create a file like this: appapiaccountsloginroutes.ts and inside this file export one function for each HTTP method that the route needs to respond to:

    Ex: export async function POST (request: Request) {}

    You can check more info here and here and maybe here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search