Search code examples
next.jsserverlessnext.js13

how to create serverless functions (get requests) with nextjs 13


I am used to create simple api endpoints via nextjs serverless functions. I had an api folder inside my pages folder which contains all my endpoints. I just created a new repository with nextjs 13 which uses the app router instead of the pages one. I don't get how to create new routes.

I found this in the docs:

import { NextResponse } from "next/server";

export async function GET(request: Request) {
  return NextResponse.json({ hello: "Next.js" });
}

So I tried to add it within app/api/route.ts, but querying localhost:3000/api/route returns me a 404 error. What did I miss?


Solution

  • In the new app router the route.ts file has special meaning and is not part of the endpoint url. So in your case for app/api/route.ts the resulting url is localhost:3000/api for localhost:3000/api/route you would need to structure it as app/api/route/route.ts or for localhost:3000/api/foo/bar it would be app/api/foo/bar/route.ts etc. The route.ts file indicates that the handler defined in that file applies to the path corresponding to the parent folder. Also the file needs to be called route.js|ts calling it something_else.ts will not work.