TanStackT
TanStack5mo ago
8 replies
urgent-maroon

How to handle notFound errors based on route param validation?

I have a lot of routes like /posts/$postId where I essentially just call a server function to get the relevant post:

// route
export const Route = createFileRoute("/posts/$postId")({
  component: RouteComponent,
  loader: async ({ context: { queryClient }, params: { postId } }) => {
    // should validate and throw notFound before get here?
    await queryClient.ensureQueryData(postQueryOptions(postId));
  },
});

// serverFn
export const getPost = createServerFn({ method: "GET" })
  .validator(z.object({ id: z.uuid() }))
  .handler(async ({ data: { id } }) => {
    const post = await db.query.posts.findFirst({
      where: { id }
      ...
    })

    if (!post) throw notFound();
    return post
  });


With this setup zod throws a validation error when the postId param is not a valid UUID - which I want because then it doesn't actually have to unnecessarily query the database. However ideally I would want to throw an error using notFound() instead in these cases so the correct not found error component is shown rather than the generic one.

I assume I'm missing some logic about how to handle this in router and it shouldn't be getting to the point that the serverFn is actually called but I've struggled to find anything relevant in the docs - hoping I'm just being dumb?
Was this page helpful?