Skip to content

Conversation

@csansoon
Copy link
Contributor

@csansoon csansoon commented Nov 19, 2025

The returned type from an API route and the expected type from a fetcher have nothing to do and could change without warning.

Although this does not completely fix that, it does improve the type safety by adding an optional type enforcement.

Let me explain with an example:

Let's say you have a hook with the following fetcher:

const fetcher = useFetcher<CompletedRuns[]>(CUSTOM_ROUTE)

You are expecting the route to return a response with the CompletedRuns[] type.

However, if the route logic changes at any point and you forget to update all hooks that use this route, you will not notice it!

Now, you can add this same type to the route, to enforce the return!

// apps/web/src/api/.../route.ts

export const GET = errorHandler<CompletedRuns[]>(
  authHandler(
    async(...) => {
      ...
      return NextResponse.json(result, { status: 200 })
    }
  )
)

Tip

You can add the generic type in any errorHandler, authHandler or adminHandler. You can even add it to all of them at the same time!

Now that you have added the CompletedRuns[] type to the handler, it will display a typecheck error if the result object does not match this defined type.

So now, you can improve the dev exp by using the same type both on the route definition and useFetcher implementation!

@csansoon csansoon force-pushed the route-handler-generic-type branch from 054fec1 to e5bbf91 Compare November 19, 2025 16:31
@csansoon csansoon force-pushed the route-handler-generic-type branch from e5bbf91 to 9efb900 Compare November 19, 2025 16:37
}

return NextResponse.json(response, { status: 200 })
return NextResponse.json(response.items, { status: 200 })
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was the bug 🐛 . Now that you're here remove response constant enterely 🔥

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants