Plain Function Handlers
Learn how to create simple API endpoints using plain JavaScript functions in Bini.js.
Plain function handlers are the simplest way to create API routes in Bini.js. They're perfect for simple endpoints that don't need complex routing or middleware.
src/app/api/hello.ts is served at /api/hello. There are no root / API routes — every file maps to a named route based on its filename.Basic Handler
Export a default function that receives the Request object. The function name doesn't matter — only the file path determines the route:
This creates an endpoint at /api/hello that responds to all HTTP methods.
Route Mapping
Your file structure directly maps to API routes:
| File Path | API Route |
|---|---|
| src/app/api/hello.ts | /api/hello |
| src/app/api/user.ts | /api/user |
| src/app/api/posts.ts | /api/posts |
| src/app/api/posts/[id].ts | /api/posts/:id |
| src/app/api/posts/index.ts | /api/posts |
| src/app/api/[...catch].ts | /api/* |
Handling HTTP Methods
Check request.method to handle different HTTP verbs:
| Method | Typical Use |
|---|---|
| GET | Retrieve data |
| POST | Create new data |
| PUT | Replace existing data |
| PATCH | Partially update data |
| DELETE | Remove data |
Reading Request Data
Access different parts of the incoming request:
Sending Responses
Return different types of responses:
Dynamic Routes
For dynamic routes, parameters are passed via the x-bini-params header:
Catch-all Routes
Handle all unmatched API routes with [...catch]:
Environment Variables
Use getEnv() and requireEnv() — both are auto-imported in API routes:
getEnv and requireEnv read from the Hono request context, resolving from the correct source on every platform automatically — Node.js, Bun, Deno, Vercel Edge, Netlify Edge, or Cloudflare Workers.| Function | Returns | Behavior |
|---|---|---|
| getEnv(key) | string | undefined | Returns undefined if missing — use ?? for defaults |
| requireEnv(key) | string | Throws immediately if missing or empty |
Error Handling
Properly handle errors in your API routes:
When to Use Plain Handlers
| Scenario | Recommendation |
|---|---|
| Single endpoint with simple logic | Plain handler |
| Quick prototypes | Plain handler |
| Simple CRUD operations | Plain handler |
| Multiple endpoints in one file | Use Hono |
| Need middleware | Use Hono |
| Complex routing patterns | Use Hono |
| Production APIs with many routes | Use Hono |
Complete Example
A full-featured plain function handler with validation, error handling, and multiple methods: