T
TanStack8mo ago
xenial-black

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 POST route using Zod with safeParse, but request.body has to be validated like so:
import { json } from "@tanstack/start";
import { createAPIFileRoute } from "@tanstack/start/api";
import { z } from "zod";

const CreatedBonusSchema = z.object({
name: z.string().min(1).max(125),
code: z.string().cuid2(),
});

export const APIRoute = createAPIFileRoute("/api/bonus")({
POST: ({ params, request }) => {
console.log("🚀 ~ APIRoute ~ request, params:", request, params);

const result = CreatedBonusSchema.safeParse(request.body);

if (!result.success) {
return json({ message: result.error.message }, { status: 400 });
}
console.log("🚀 ~ APIRoute ~ result:");

return json({ message: "Created bonus!", body: result.data });
}
}
import { json } from "@tanstack/start";
import { createAPIFileRoute } from "@tanstack/start/api";
import { z } from "zod";

const CreatedBonusSchema = z.object({
name: z.string().min(1).max(125),
code: z.string().cuid2(),
});

export const APIRoute = createAPIFileRoute("/api/bonus")({
POST: ({ params, request }) => {
console.log("🚀 ~ APIRoute ~ request, params:", request, params);

const result = CreatedBonusSchema.safeParse(request.body);

if (!result.success) {
return json({ message: result.error.message }, { status: 400 });
}
console.log("🚀 ~ APIRoute ~ result:");

return json({ message: "Created bonus!", body: result.data });
}
}
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:
(property) POST?: StartAPIMethodCallback<"/api/bonus"> | undefined

(property) POST?: StartAPIMethodCallback<"/api/bonus"> | undefined


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:
const { sessionClaims, userId } = await getAuth(request);
if (!userId) return new Response("Unauthorized", { status: 401 });

const { sessionClaims, userId } = await getAuth(request);
if (!userId) return new Response("Unauthorized", { status: 401 });


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-black
xenial-blackOP8mo ago
Bumping this up so someone sees it 😅
adverse-sapphire
adverse-sapphire8mo 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
adverse-sapphire8mo 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-black
xenial-blackOP8mo ago
Sweet thank you so much 🙏
other-emerald
other-emerald6mo 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
optimistic-gold6mo ago
yeah this will come soon

Did you find this page helpful?