---
title: "Type-Safe RPC Client"
description: "The Type-Safe RPC Client (hc) is a powerful feature that allows frontend developers, browser clients, and external applications to consume Hono backend APIs with full, automatic TypeScript type inf..."
last_updated: "2026-11-24T23:01:51.035909+00:00"
canonical_url: "https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/user-guide/type-safe-rpc-client"
---

## Overview

### Introduction to Type-Safe RPC
The Type-Safe RPC Client (`hc`) is a powerful feature that allows frontend developers, browser clients, and external applications to consume Hono backend APIs with full, automatic TypeScript type inference. By passing your backend application type (`typeof app`) to `hc`, the client generates a fully typed proxy object. This means your editor will autocomplete your URL paths, validate your request bodies, query parameters, and route parameters, and correctly type the response data without writing manual type definitions.

```mermaid
flowchart TD
    A["Hono Backend app"] -->|"Export type typeof app"| B["Frontend Client"]
    B -->|"hc<typeof app>('url')"| C["Type-Safe RPC Client Proxy"]
    C -->|"Autocomplete & Type Check"| D["API Request"]
```

### Key Concepts
Before using the Type-Safe RPC Client, it helps to understand the main building blocks provided by the library:

- **`hc` (Hono Client)**: The core function used to instantiate a type-safe RPC client. It accepts a base URL and an optional configuration object, returning a typed proxy corresponding to your backend routes.
- **`parseResponse`**: A helper utility that takes an `hc` request promise, checks if the HTTP status code is successful, handles errors automatically by throwing a structured `DetailedError`, and extracts the typed response data.
- **`ClientRequestOptions`**: An options object passed to client requests or initialization, allowing you to configure custom fetch functions, headers, request initializers, and search parameter serializers.

---

## Getting Started with `hc`

### 1. Export your Hono app type from the backend
Ensure your backend Hono application instance is exported so that frontend code can import its type definition.

```ts
// backend.ts
import { Hono } from 'hono'

const app = new Hono()
  .get('/posts/:id', (c) => {
    const id = c.req.param('id')
    return c.json({ id, title: 'Hello Hono' })
  })

export type AppType = typeof app
export default app
```

### 2. Instantiate the client on the frontend
Import the `hc` function from the client module and pass your backend app type as a generic parameter along with your API's base URL.

```ts
// client.ts
import { hc } from 'hono/client'
import type { AppType } from './backend'

const client = hc<AppType>('http://localhost:8787')
```

### 3. Make type-safe API requests
Call the methods on your client proxy matching your route structure. TypeScript will verify parameters, query strings, and payloads.

```ts
const res = await client.posts[':id'].$get({
  param: { id: '123' }
})

if (res.ok) {
  const data = await res.json()
  // data is automatically typed as: { id: string; title: string; }
}
```

---

## Configuration Options

### Request Options Overview
When initializing `hc` or executing requests, you can pass a `ClientRequestOptions` object to customize behavior.

| Option Key | Type | Description |
| :--- | :--- | :--- |
| `fetch` | `typeof fetch \| HonoRequest` | Custom fetch implementation or handler function for testing or SSR. |
| `webSocket` | `(...args) => WebSocket` | Custom WebSocket factory function. |
| `init` | `RequestInit` | Standard `RequestInit` options passed directly to the underlying fetch call. |
| `headers` | `Record<string, string> \| (() => ...)` | Custom headers or a function returning headers (supporting async values). |
| `buildSearchParams` | `BuildSearchParamsFn` | Custom function to serialize query parameters into `URLSearchParams`. |

> [!TIP]
> Use the `headers` option to supply authentication tokens dynamically by passing a function that returns a header record or a Promise resolving to a header record.

---

## Working with `parseResponse`

### Response Parsing and Error Handling
To streamline error handling and data extraction, Hono provides `parseResponse`. Instead of manually checking `res.ok`, calling `.json()`, and dealing with error responses, `parseResponse` automatically validates the status code and unpacks the payload.

```ts
import { hc, parseResponse } from 'hono/client'
import type { AppType } from './backend'

const client = hc<AppType>('http://localhost:8787')

async function getPost() {
  try {
    // Automatically throws a DetailedError if the response is not 2xx
    const post = await parseResponse(client.posts[':id'].$get({
      param: { id: '123' }
    }))
    
    console.log(post.title)
  } catch (error) {
    console.error('Failed to fetch post:', error)
  }
}
```

> [!WARNING]
> The `init` option in `ClientRequestOptions` takes highest priority and can overwrite properties that Hono sets automatically, such as `body`, `method`, or `headers`. If you only want to add custom headers, prefer using the `headers` option instead of `init`.

## Related

- [Request Data Validation](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/user-guide/request-data-validation)
- [Routing and Handlers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/user-guide/routing-and-handlers)


## Sitemap

See the full [sitemap](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/llms.txt) for all pages in this wiki.
