Corsair
Integrations

Hono

Integrate Corsair with Hono for lightweight, edge-compatible APIs

Hono

Corsair integrates with Hono for lightweight, edge-compatible APIs.

Installation

npm install corsair hono
npx corsair init --framework hono

Setup

Create a Hono app with Corsair:

src/index.ts
import { Hono } from 'hono'
import { corsair } from './lib/corsair'

const app = new Hono()

app.post('/api/corsair', async c => {
  return corsair.handle(c.req.raw)
})

export default app

Configuration

src/lib/corsair.ts
import { createCorsair } from 'corsair'

export const corsair = createCorsair({
  database: {
    type: 'postgresql',
    url: process.env.DATABASE_URL,
  },
})

With Authentication

Add auth middleware:

src/index.ts
import { Hono } from 'hono'
import { jwt } from 'hono/jwt'
import { corsair } from './lib/corsair'

const app = new Hono()

// Protect Corsair routes
app.use(
  '/api/corsair',
  jwt({
    secret: process.env.JWT_SECRET!,
  })
)

app.post('/api/corsair', async c => {
  const payload = c.get('jwtPayload')

  return corsair.handle(c.req.raw, {
    context: {
      userId: payload.sub,
      role: payload.role,
    },
  })
})

export default app

Edge Runtime

Deploy to Cloudflare Workers:

src/index.ts
import { Hono } from 'hono'
import { corsair } from './lib/corsair'

const app = new Hono()

app.post('/api/corsair', async c => {
  return corsair.handle(c.req.raw)
})

export default app
wrangler.toml
name = "my-app"
main = "src/index.ts"
compatibility_date = "2024-01-01"

[env.production]
vars = { DATABASE_URL = "..." }

Client Setup

src/client.tsx
import { createCorsairClient, CorsairProvider } from 'corsair/client'

const corsairClient = createCorsairClient({
  apiUrl: '/api/corsair',
})

export function App() {
  return (
    <CorsairProvider client={corsairClient}>{/* Your app */}</CorsairProvider>
  )
}

CORS

Enable CORS for frontend clients:

src/index.ts
import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { corsair } from './lib/corsair'

const app = new Hono()

app.use(
  '/api/*',
  cors({
    origin: ['http://localhost:3000'],
    credentials: true,
  })
)

app.post('/api/corsair', async c => {
  return corsair.handle(c.req.raw)
})

export default app

With Context

Pass request context to Corsair:

src/index.ts
app.post('/api/corsair', async c => {
  return corsair.handle(c.req.raw, {
    context: {
      ip: c.req.header('cf-connecting-ip'),
      userAgent: c.req.header('user-agent'),
      userId: c.get('userId'),
    },
  })
})