Search code examples
next.jsnext.js14

Nextjs 14 always responds with 404 Not Found when using API routes


I am very new to next am running the following API route code from nextjs documentation (this is a file named "hello.js" in the api folder)

export default function handler(req, res) {
  res.status(200).json({ message: 'Hello from Next.js!' })
}

but fail miserably always getting 404 not found.

Of course, if I use a Route Handlers in the App Router it works fine. Can you please tell me how I can make this API route to work?


Solution

  • are you using app router or page router ? if you are using

    Pages Router

    it has a folder name pages/

    and usually in the page folder there is folder name api/ then inside that you can make an api route with hello.js, hello.ts.

    App Router

    if you use App router it usually have app/ folder

    and the way we are making the route is using route handler, and we can do it almost anywhere on the app

    as long as you use route.ts or route.js, and if you want to have pages in app router then we use /name-of-the-path/pages.tsx

    So if you want to have domain.com/hello then the folder is /hello/page.tsx

    and if you want to have domain.com/api/hello then the folder is /api/hello/route.ts

    you can't however use page.tsx and route.ts file on the same folder.

    Read more the migration here :

    https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration