Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 811
Dr. Arjen Avatar asked Jul 28 '26 08:07

Dr. Arjen


2 Answers

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!

like image 197
Fatorice Avatar answered Jul 31 '26 00:07

Fatorice


This is a follow-up to Fatorice's response. Here is what you need to change:

The following (page router):

// Filename: pages/api/hello.ts

import type { NextApiRequest, NextApiResponse } from "next";

type ResponseData = {
  message: string;
};

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<ResponseData>
) {
  res.status(200).json({ message: "Hello from Next.js!" });
}

Needs to be changed to (app router):

// Filename: app/api/hello/route.ts

function requestHandler(_request: Request): Response {
  return Response.json({ message: "Hello from Next.js!" });
}

export { requestHandler as GET };

If you are using a version of TypeScript < 5.2, you need to change the signature an usage to:

// Filename: app/api/hello/route.ts

import { NextRequest, NextResponse } from "next/server";

function requestHandler(_request: NextRequest): NextResponse {
  return NextResponse.json({ message: "Hello from Next.js!" });
}

export { requestHandler as GET };

These types also provide some additional features that do not come with the standard Request and Response types.

Extended NextRequest and NextResponse APIs

In addition to supporting native Request and Response. Next.js extends them with NextRequest and NextResponse to provide convenient helpers for advanced use cases.

like image 36
Mr. Polywhirl Avatar answered Jul 31 '26 00:07

Mr. Polywhirl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!