Type-Safe JSON Responses in Hono
What you'll learn: How to use Hono's c.json() method with explicit return types to guarantee your API responses match their expected shape at compile time.
The Problem: JSON Responses Without Type Safety
When building APIs, you typically return JSON data. Without type safety, there's nothing stopping you from accidentally sending the wrong shape of data—maybe a missing field, a typo in a property name, or the wrong data type entirely. The client expects one thing, but gets another.
How c.json() Provides Type Safety
Hono's context object (c) has a .json() method that returns a typed response. When you define your response type explicitly and use c.json(), TypeScript verifies that the object you're passing matches that exact shape:
import { Hono } from 'hono';
type UserResponse = {
id: number;
username: string;
email: string;
};
const app = new Hono();
app.get('/user/:id', (c) => {
const user: UserResponse = {
id: 1,
username: 'alice',
email: 'alice@example.com'
};
return c.json(user); // TypeScript knows this is UserResponse
});
Explicit Return Type for Route Handlers
For even stronger guarantees, explicitly type the return value of your route handler. This creates a contract that must be honored:
app.get('/user/:id', (c): Response => {
// Return type must satisfy Response with UserResponse body
const user: UserResponse = {
id: 1,
username: 'alice',
email: 'alice@example.com'
// TypeScript error if you forget 'email'!
};
return c.json(user);
});
If you try to return an object missing the email field or with an extra unexpected property, TypeScript catches it immediately—before any client code ever runs.
Think of It Like a Mold
Imagine your response type is a cookie cutter. The c.json() method is the dough. TypeScript ensures the dough fits perfectly into the cutter shape before any cookies get baked. No surprises when the cookies come out of the oven.
Key Takeaway: Using c.json() with explicitly typed response objects turns your API contracts from documentation into compile-time guarantees, catching response shape mismatches before they reach production.