Next.js Discord

Discord Forum

"Failed to collect page data" on dynamic segment route handler

Answered
Crème D’Argent posted this in #help-forum
Open in Discord
Crème D’ArgentOP
I have a route handler, which is defined under app/api/[id]/route.ts. This folder does not have a layout.ts nor a page.ts, it is only a route handler. When building for production, after collection page information occurs, a build error is thrown for this path. This route only contains a single GET method, which relies on the dynamic id parameter

The error is coming from a data validation, where we throw an error if the id param is invalid. Why is Next attempting to statically build my dynamic route handler?
Answered by Crème D’Argent
It turned out that the problem was a missing environment variable of mine which I validate with Zod, and it just wasn't clear at all that that was what was causing the error. So, word of caution in case you validate the presence of environment variables, best to include some clear error messaging in the check.
View full answer

5 Replies

Crème D’ArgentOP
Here's the relevant code:

export const GET = async (
  _: NextRequest,
  { params }
) {
  // error is intentionally thrown if `params.id` is undefined
  const id = z.string().parse(params.id); 

  const post = await postService.getPost(id);

  return NextResponse.json({
    data: post,
  });
};
Also I tried and it's wokring with my code
Try to update latest version of NextJS v14
Crème D’ArgentOP
It turned out that the problem was a missing environment variable of mine which I validate with Zod, and it just wasn't clear at all that that was what was causing the error. So, word of caution in case you validate the presence of environment variables, best to include some clear error messaging in the check.
Answer