Chapter 11
Cookies and Headers
Work with request metadata and small browser state.
Cookies and Headers
Headers describe a request or response. Cookies are small pieces of browser state sent through headers.
Request headers
Use c.req.header() to read incoming headers.
app.get('/language', (c) => {
const language = c.req.header('Accept-Language') ?? 'unknown'
return c.text(`Preferred language: ${language}`)
})
Use this for metadata such as content type, user agent, authorization, or language preferences.
Response headers
Use c.header() to add response headers.
app.get('/chapters.json', (c) => {
c.header('Cache-Control', 'public, max-age=300')
return c.json({ ok: true })
})
For site-wide headers, prefer middleware so each route does not repeat the same setup.
Cookie helpers
Hono includes helpers for reading and writing cookies.
import { getCookie, setCookie } from 'hono/cookie'
app.get('/theme', (c) => {
const theme = getCookie(c, 'theme') ?? 'light'
return c.text(`Current theme: ${theme}`)
})
app.post('/theme/dark', (c) => {
setCookie(c, 'theme', 'dark', {
httpOnly: true,
sameSite: 'Lax',
secure: true,
})
return c.redirect('/')
})
Cookies are useful for lightweight preferences and session identifiers. Avoid storing sensitive application data directly in a cookie value.