API Routes Overview
Learn how to create backend API endpoints in Bini.js using plain functions or Hono.
Bini.js allows you to create API endpoints directly in your project. Place files in src/app/api/ and they automatically become API routes at /api/*. The filename maps directly to the route — hello.ts becomes /api/hello, users.ts becomes /api/users.
default export. Bini.js uses the default export to handle requests. Named exports will not work.File Structure
The filename (without extension) becomes the last segment of the URL path under /api/:
/api route. Every API file maps to a named path — use posts/index.ts if you need a route at /api/posts.Plain Function Handler
The simplest way to create an API route is to default export a handler function that checks the HTTP method:
The handler receives the native Request object. Check request.method to handle different HTTP verbs.
Hono Integration
For more complex APIs, use Hono. Create a Hono app and default export it. Write routes without the /api prefix — bini-router strips it before your handler sees the request.
Hono Middleware
Hono provides built-in middleware for common tasks:
| Middleware | Purpose |
|---|---|
| cors | Cross-Origin Resource Sharing |
| logger | Request logging |
| jwt | JWT authentication |
| prettyJSON | Pretty JSON responses |
| timeout | Request timeout |
Dynamic API Routes
Use square brackets for dynamic segments, just like page routes:
For plain function handlers with dynamic routes, parameters are passed via the x-bini-params header:
Catch-all API Routes
Use [...catch] to handle all unmatched API routes:
Environment Variables
API routes use getEnv(c, key) and requireEnv(c, key) from bini-env. Both read directly from the Hono request context — they work across every runtime without code changes.
c explicitly. Cast it once at the top as const ctx = c as any, then use ctx throughout.The pattern in three steps:
Request & Response
API routes use standard Web APIs for requests and responses:
CORS
CORS is enabled by default for all API routes:
With Hono, configure CORS per route:
Deployment
API routes work across all deployment platforms. To deploy, run:
This will prompt you to select your hosting platform:
- Node.js — Runs via bini-server
- Netlify — Edge Functions (Deno)
- Vercel — Edge Runtime
- Cloudflare — Workers
- Deno — Deno Deploy
npm run deploy and select your platform. bini-deploy will generate the appropriate entry files and configuration for your chosen platform.