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
Since version
v13.2
, we have Route Handlers in theapp
folder. It works like pages, but the file for the segment should be calledroute.js
orroute.ts
. For example:And at this point, you can access it as any API route, for example, with
fetch("/list-items")
. While going to/
renderspage.tsx
.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
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.
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