Validating Request Body, Typing API Routes, and Middleware Authentication in TanStack Start API
Hi, I’m using TanStack Start API routes and have a few questions:
1. Validating Request Body
I’m currently validating the request body in a
2. Typing API Routes
When defining an API route, the
Shouldn’t it infer the response type as
3. Middleware for Authentication (Clerk)
Currently, I have to call
Is there a way to apply authentication as middleware so I don’t have to repeat
Any guidance would be appreciated! Thanks!
1. Validating Request Body
I’m currently validating the request body in a
POST
route using Zod with safeParse
, but request.body
has to be validated like so:
Is there a built-in way to automatically parse request.body
, or do I need to manually handle this before entering the endpoint?2. Typing API Routes
When defining an API route, the
POST
method gets the type:Shouldn’t it infer the response type as
{ message: string, body: { name: string, code: string } }
? Is there a way to make the response type more specific?3. Middleware for Authentication (Clerk)
Currently, I have to call
getAuth(request)
inside every endpoint to check authentication:Is there a way to apply authentication as middleware so I don’t have to repeat
getAuth
in every route?Any guidance would be appreciated! Thanks!
6 Replies
xenial-blackOP•8mo ago
Bumping this up so someone sees it 😅
adverse-sapphire•8mo ago
1 - Currently, we don't have anything special for API routes. It's bog standard Request/Response.
We thought about adding a bunch of stuff for doing validation and whatnot, but decided not to add it in for now, because the demand at the time was to get API routes shipped.
Now, I don't really think we'll be adding it in, because of how API routes are functionally different to general application Routes.
2 - Not sure about this one. Would have to look into it.
Easiest option for now is
NonNullable<...>
adverse-sapphire•8mo ago
3 - API routes do not have middleware at the moment.
For now, you'll need to get by with an abstracted function.
Start's server functions however, do have middleware - https://tanstack.com/start/latest/docs/framework/react/middleware#defining-middleware-for-server-functions
Middleware | TanStack Start React Docs
What is Server Function Middleware? Middleware allows you to customize the behavior of server functions created with createServerFn with things like shared validation, context, and much more. Middlewa...
xenial-blackOP•8mo ago
Sweet thank you so much 🙏
other-emerald•6mo ago
it would be great if we could get path, query params, and request body validation as you have for server functions. We are still making api routes for other client types to access.
optimistic-gold•6mo ago
yeah this will come soon