i have a question, i’ve spend the past 2 hours looking for an answer on the web but i haven’t find one.
well im using Nextjs with the new App router.
when a user navigate to an undefined route in app/api.
Ex: (localhost:3000/api/useer/1235)
(userr= does not exist)
next will respond with a 404 html page which is correct,
but instead of returning an html page and because its an api call
i would like to return a Json response
to the user.
any help or suggestion is appreciated , Thank you.
2
Answers
Catch-all
API did not help, so I ended up setting checkpoints in themiddleware
file. If a user tries to navigate to a route outside the routing list, a JSON response with status 404 will be returned. It may be a silly approach, but that's all I could think of for the moment until an expert inNext.js
or one of its engineers comes to the rescue.Thank you
You can use a Catch All API Route/Optional Catch All API Route to handle all non-existent requests. Request pages that actually exist will take precedence over this route so it won’t mess with your existing API routes.
https://nextjs.org/docs/pages/building-your-application/routing/api-routes#catch-all-api-routes
Then put whatever JSON response you want in there.