Path Parameters and Validation in Hono
What you'll learn: How Hono automatically infers types from route parameter patterns like /users/:id, giving you compile-time safety when accessing dynamic URL segments.
Why Path Parameters Need Types
When you define a route like /users/:id in most frameworks, extracting that id requires string access with no compile-time guarantees. Hono flips this: it reads your route pattern and automatically knows which parameters exist.
How c.req.param() Works with Type Inference
In Hono, when you define a route with parameters, the framework tracks those parameter names at the type level:
app.get('/users/:id', (c) => {
const id = c.req.param('id'); // id is typed as string
return c.json({ userId: id });
});
Notice you didn't annotate id — Hono inferred it exists from the route definition. If you try c.req.param('name'), TypeScript will error because 'name' isn't in /users/:id.
Multiple Parameters with Automatic Inference
app.get('/posts/:postId/comments/:commentId', (c) => {
const postId = c.req.param('postId'); // string
const commentId = c.req.param('commentId'); // string
// c.req.param('wrong') // ❌ TypeScript error: parameter doesn't exist
return c.text(`Post ${postId}, Comment ${commentId}`);
});
The route pattern defines a contract — Hono's types enforce it.
Think of It Like Object Key Safety
Imagine your route is an object: { postId: string, commentId: string }. Hono's c.req.param() is like a type-safe property accessor — you can only access keys that actually exist, and TypeScript autocompletes them for you.
Validation Beyond Types
Remember: TypeScript types disappear at runtime. While Hono gives you compile-time safety that the parameter name exists, you still need runtime validation if you care about the parameter's content (e.g., ensuring id is a number, not "abc"). Combine Hono's type inference with a validator like Zod for full safety.
Key Takeaway: Hono's c.req.param() automatically infers which path parameters exist from your route definitions, catching typos and missing parameters at compile time before they become runtime bugs.