hantoren
hantoren

Reputation: 1245

How to Return JSON in Next.js not-found.tsx?

I am working on a Next.js 14 project where I've set up a custom 404 page using the not-found.tsx file placed in the app root. In cases where an endpoint is not found, I'd like to return a simple JSON object instead of the default HTML response.

In regular API routes, I can easily achieve this using return NextResponse.json({}), but I'm having difficulty figuring out how to accomplish the same in the not-found.tsx file.

Upvotes: 2

Views: 287

Answers (1)

aryomuzakki
aryomuzakki

Reputation: 106

I have the same case and ended up here.

Now I come up with a solution, that is to use Catch-all Segments

use [...slug] as your folder name to catch all route you haven't defined, and route.js file inside the folder

your folder path will be: /api/[...slug]/route.js

this will handle route for: /api/other/, or api/any/nested/

your route.js file could be like this:

const notFoundJSON = (request, params) => {
  return Response.json(
    { message: `Route Not Found '/api/${params?.slug?.join("/") || ""}/'` },
    { status: 404 },
  )
}

export function GET(request, { params }) {
  return notFoundJSON(request, params);
}
export function POST(request, { params }) {
  return notFoundJSON(request, params);
}
export function PUT(request, { params }) {
  return notFoundJSON(request, params);
}
export function DELETE(request, { params }) {
  return notFoundJSON(request, params);
}

if you also want to handle route for /api/ , you can also use Optional Catch-all Segment by renaming folder from [...slug] to [[...slug]]

Note: not-found file is required to exist in app root

Upvotes: 2

Related Questions