Add Hono to TanStack Start

Mount a Hono API in TanStack Start, validate requests, and protect a project route with a server-verified user.

By Antoine RossPublished

You can serve a Hono API from the same TanStack Start app as your React pages. You do not need Hono for a few endpoints: TanStack Start server routes handle those, as in testing API authorization. Hono helps when you want one router with shared middleware across many endpoints. This example adds endpoints to create and list a signed-in user's projects. It keeps identity checks in the API, so hiding a button is not the only protection.

Before you start

Start with an existing TanStack Start app that can sign users in and verify them on the server. The API needs that to know whose projects to return. This example uses the cookie-backed Supabase helper from Supabase authentication in TanStack Start and a confirmed test user. If your app uses another authentication library, keep it: only the currentUserId function below is provider-specific. Install Hono:

bun add hono

The example below stores projects in process memory to make the HTTP path easy to try. It is for local learning only: data disappears when the process restarts and is not shared between instances. Use a database and migrations before relying on the data. Hono's documentation describes its request and response API.

Create the API

Set APP_ORIGIN in the server environment to the exact origin of your local app, such as http://localhost:3000. In production, set it to your public HTTPS origin. Create :

import '@tanstack/react-start/server-only'
import { Hono } from 'hono'
import { supabaseServer } from '../lib/supabase-server'

type Project = { id: string; ownerId: string; name: string }
const projects = new Map<string, Project>()

// The only provider-specific function. With another auth library, return its
// server-verified user ID here, or null when the request is not signed in.
async function currentUserId() {
  const { data, error } = await supabaseServer().auth.getUser()
  if (error || !data.user || data.user.is_anonymous) return null
  return data.user.id
}
export const api = new Hono().basePath('/api')
api.use('*', async (c, next) => {
  await next()
  c.header('Cache-Control', 'private, no-store')
  c.header('Vary', 'Cookie')
})

api.get('/projects', async (c) => {
  const userId = await currentUserId()
  if (!userId) return c.json({ error: 'Authentication required' }, 401)
  const own = [...projects.values()]
    .filter(project => project.ownerId === userId)
    .map(({ id, name }) => ({ id, name }))
  return c.json({ data: own }, 200, { 'Cache-Control': 'private, no-store' })
})

api.post('/projects', async (c) => {
  const origin = process.env.APP_ORIGIN
  if (!origin || c.req.header('Origin') !== origin ||
      c.req.header('Content-Type')?.split(';', 1)[0].trim().toLowerCase() !== 'application/json') {
    return c.json({ error: 'Request denied' }, 403)
  }
  const userId = await currentUserId()
  if (!userId) return c.json({ error: 'Authentication required' }, 401)
  let input: unknown
  try { input = await c.req.json() } catch {
    return c.json({ error: 'Invalid JSON' }, 400)
  }
  if (typeof input !== 'object' || input === null || Array.isArray(input) ||
      Object.keys(input).some(key => key !== 'name') ||
      !('name' in input) || typeof input.name !== 'string') {
    return c.json({ error: 'Expected a project name' }, 400)
  }
  const name = input.name.trim()
  if (!name || name.length > 80) return c.json({ error: 'Name must be 1 to 80 characters' }, 400)
  const project = { id: crypto.randomUUID(), ownerId: userId, name }
  projects.set(project.id, project)
  return c.json({ data: { id: project.id, name } }, 201, { 'Cache-Control': 'private, no-store' })
})

api.get('/projects/:id', async (c) => {
  const userId = await currentUserId()
  if (!userId) return c.json({ error: 'Authentication required' }, 401)
  const project = projects.get(c.req.param('id'))
  if (!project || project.ownerId !== userId) return c.json({ error: 'Not found' }, 404)
  return c.json({ data: { id: project.id, name: project.name } }, 200, { 'Cache-Control': 'private, no-store' })
})

api.patch('/projects/:id', async (c) => {
  const origin = process.env.APP_ORIGIN
  if (!origin || c.req.header('Origin') !== origin ||
      c.req.header('Content-Type')?.split(';', 1)[0].trim().toLowerCase() !== 'application/json') {
    return c.json({ error: 'Request denied' }, 403)
  }
  const userId = await currentUserId()
  if (!userId) return c.json({ error: 'Authentication required' }, 401)
  const project = projects.get(c.req.param('id'))
  if (!project || project.ownerId !== userId) return c.json({ error: 'Not found' }, 404)
  let input: unknown
  try { input = await c.req.json() } catch { return c.json({ error: 'Invalid JSON' }, 400) }
  if (typeof input !== 'object' || input === null || Array.isArray(input) ||
      Object.keys(input).some(key => key !== 'name') ||
      !('name' in input) || typeof input.name !== 'string') {
    return c.json({ error: 'Expected a project name' }, 400)
  }
  const name = input.name.trim()
  if (!name || name.length > 80) return c.json({ error: 'Name must be 1 to 80 characters' }, 400)
  project.name = name
  return c.json({ data: { id: project.id, name } }, 200, { 'Cache-Control': 'private, no-store' })
})

The server derives ownerId from the verified session, not the request body. List results are filtered by that ID. The single-project GET and PATCH check the stored owner before returning or changing the record, and return the same 404 for missing and other users' records. This is a single-owner example, not an organization role model. A valid login alone is not enough.

The exact-origin and JSON checks narrow cross-site request exposure for this browser-oriented example. Configure the trusted origin yourself; do not derive it from an untrusted request header. Add body-size limits, rate limits, durable storage, and a reviewed CSRF strategy for your deployment. OWASP's CSRF guidance explains the tradeoffs.

Forward requests from TanStack Start

Create :

import { createFileRoute } from '@tanstack/react-router'

const handle = async ({ request }: { request: Request }) => {
  const { api } = await import('../../api/app')
  return api.fetch(request)
}

export const Route = createFileRoute('/api/$')({
  server: { handlers: { GET: handle, POST: handle, PATCH: handle } },
})

The /api/$ catch-all sends the original request to Hono. The dynamic import keeps server-only dependencies behind the server handler. Restart the dev server if your route generator has not picked up the file. See TanStack Start server routes.

Check the route

Sign in at /sign-in, then open your browser's developer console on the same origin and run:

await fetch('/api/projects', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'First project' }),
}).then(async response => [response.status, await response.json()])

Expect 201 and the new project's ID and name. Then run await fetch('/api/projects').then(r => r.json()) and confirm that the list contains it. Sign out and request the list again; expect 401. A different test user should see an empty list, not the first user's project.

Copy only the project ID, sign in as the second user, and run this from the same-origin console, replacing the placeholder with that ID:

const path = '/api/projects/' + encodeURIComponent('REPLACE_WITH_PROJECT_ID')
const read = await fetch(path)
const update = await fetch(path, {
  method: 'PATCH',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Wrong owner' }),
})
console.log({ read: read.status, update: update.status })

Both statuses should be 404. Sign back in as the owner and confirm the name is unchanged. The authorization testing guide expands these checks. Never paste session cookies into the console or a support request.

If the POST returns 403, compare the browser's origin and APP_ORIGIN, including scheme and port. If it returns 401, check the sign-in and response cookies. A 201 only proves this process accepted the write, not that data will survive a restart.

The CoreMVP TanStack Start premium template mounts Hono in the same runtime and supplies a durable Projects path with validation, organization membership checks, and server-side permissions. You still configure and own your database and organization rules. See the project structure guide.