reactjstypescriptnext.js13

Next.js api router throws 404


I am new to Next.js and I'm having trouble getting my API to work properly. I've set up a test endpoint at src/app/api/hello.ts with a basic response. However, when I try to access example.com/api/hello, I'm getting a 404 page instead of the expected response. Can anyone help me troubleshoot this issue? Here's the code for my endpoint:

import type { NextApiRequest, NextApiResponse } from 'next'

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  res.status(200).json({ name: 'John Doe' })
}

Note: I use auth0 for authentication and the /api/auth/[auth0]/ works just fine.


Solution

  • It seems like you are using the new app router of next.js 13. When using app router with api routes, you have to follow the naming convention for api routes: app/api/[ROUTE_PATH]/route.ts. So try to move the contents of your current route handler to src/app/api/hello/route.ts. Using the new app router, the signature of the route handler changed as well: instead of one handler exported as default, you will have to export a function for each HTTP method your route supports (e.g. GET, POST, PUT, ...), which accepts a single parameter of type Request. I hope this helped you!