skip to Main Content

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


  1. Chosen as BEST ANSWER

    Catch-all API did not help, so I ended up setting checkpoints in the middleware 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 in Next.js or one of its engineers comes to the rescue.

    Thank you


  2. 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

    pages/api/post/[…slug].js matches /api/post/a, but also
    /api/post/a/b, /api/post/a/b/c and so on.

    Then put whatever JSON response you want in there.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search