DocsPluginsShowcaseReleases
npmStar us on GitHub

Getting Started

IntroductionInstallationProject StructureLayouts and PagesLinking and Navigating

Routing

Folder-Based RoutingFile-Based RoutingDynamic RoutesParallel RoutesIntercepting RoutesCatch-All RoutesMDX & Markdown Pages

Special Files

Loading UIError BoundariesTemplateDefaultNot Found

Data Fetching

LoadersActionsAccessing Route Data

Metadata

Metadata & SEOOpen Graph & TwitterIcons & Favicons

API Routes

API Routes OverviewPlain Function HandlersHono IntegrationDynamic API Routes

Environment Variables

OverviewPrefixes & Client ExposureUsing in API Routes

Styling

CSS OverviewTailwind CSSCSS Modules

Platforms

WebWindowsmacOSLinuxAndroidiOS

Deployment

Deployment OverviewProduction ServerStatic ExportHosting Providers

A native React framework for building cross-platform applications from a single codebase.

Resources

  • Documentation
  • Plugins
  • Showcase
  • Releases

Community

  • GitHub Discussions
  • Reddit
  • Discord
  • LinkedIn

More

  • npm
  • GitHub
  • Issues
  • License

© 2026 Bini Cooperation.

Plain Function Handlers

Simple API endpoints with a default-exported Request → Response function.

Overview

Plain function handlers are the simplest way to create API routes. Export a function from a file in src/app/api/ and it becomes an endpoint at /api/*. Ideal for single endpoints that do not need Hono middleware or nested routing.

File-based routing: src/app/api/hello.ts is served at /api/hello. There is no bare /api root route.

Basic Handler

Export a default function that receives a Request and a context object. The file path sets the route - the function name does not matter.

src/app/api/hello.ts
export default function handler(request: Request) {
  return Response.json({ message: 'hello', method: request.method })
}

This creates /api/hello and responds to all HTTP methods unless you branch on request.method.

Route Mapping

File structure maps directly to API paths:

app
api
ƒhello.ts
ƒusers.ts
posts
ƒindex.ts
ƒ[id].ts
ƒ[...catch].ts
/api/hello
/api/users
/api/posts
/api/posts/:id
/api/*
File PathAPI Route
src/app/api/hello.ts/api/hello
src/app/api/users.ts/api/users
src/app/api/posts/index.ts/api/posts
src/app/api/posts/[id].ts/api/posts/:id
src/app/api/[...catch].ts/api/*

Request Context

Every handler receives a second argument with the route context. Use it for path params, query parameters, and runtime env bindings.

FieldTypeDescription
paramsobjectDynamic route params (e.g. { id: "123" })
searchParamsURLSearchParamsQuery string parameters
envanyRuntime env bindings (or process.env on Node)
waitUntil?functionExtends the request lifetime for background work

Handling HTTP Methods

Branch on request.method for different verbs, or export per-method handlers (GET, POST, etc.) instead of a default function.

src/app/api/posts.ts
export default function handler(request: Request) {
  if (request.method === 'GET') {
    return Response.json({ posts: [] })
  }
  if (request.method === 'POST') {
    return Response.json({ message: 'Post created' }, { status: 201 })
  }
  if (request.method === 'PUT') {
    return Response.json({ message: 'Post updated' })
  }
  if (request.method === 'DELETE') {
    return Response.json({ message: 'Post deleted' })
  }
  return Response.json({ error: 'Method not allowed' }, { status: 405 })
}
MethodTypical Use
GETRetrieve data
POSTCreate new data
PUTReplace existing data
PATCHPartially update data
DELETERemove data

Per-Method Exports

Instead of one default function that branches on request.method, export a separate function for each HTTP verb. Each one is a plain function that receives the same Request and context object, and returns a Response.

src/app/api/posts.ts
export function GET(request: Request) {
  return Response.json({ posts: [] })
}

export async function POST(request: Request) {
  const body = await request.json()
  return Response.json({ message: 'Post created', body }, { status: 201 })
}

export function DELETE(request: Request) {
  return Response.json({ message: 'Post deleted' })
}

The context object is passed as the second argument, exactly like a default function:

src/app/api/posts/[id].ts
export function GET(
  request: Request,
  { params }: { params: { id: string } }
) {
  return Response.json({ id: params.id })
}
BehaviorDetails
Supported exportsGET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
Unhandled methodsReturn 405 with an Allow header
HEAD fallbackFalls back to GET when no HEAD export exists
PrecedenceMethod exports take precedence over a default export

Reading Request Data

Body, headers, and query params:

src/app/api/echo.ts
export default async function handler(request: Request) {
  const body = await request.json().catch(() => null)
  const userAgent = request.headers.get('User-Agent')
  const url = new URL(request.url)
  const page = url.searchParams.get('page')

  return Response.json({
    method: request.method,
    body,
    headers: { userAgent },
    query: { page },
  })
}

Sending Responses

Common response patterns:

src/app/api/responses.ts
export default function handler(request: Request) {
  // JSON
  return Response.json({ message: 'Hello JSON' })

  // Plain text
  // return new Response('Hello Text', {
  //   headers: { 'Content-Type': 'text/plain' },
  // })

  // Custom status
  // return Response.json({ message: 'Created' }, { status: 201 })

  // Redirect
  // return Response.redirect('https://example.com', 302)
}

Dynamic Routes

Path params are available in the context object, not a header. Use { params } as the second argument:

src/app/api/posts/[id].ts
export default function handler(
  request: Request,
  { params }: { params: { id: string } }
) {
  if (request.method === 'GET') {
    return Response.json({ id: params.id, title: `Post ${params.id}` })
  }

  return Response.json({ error: 'Method not allowed' }, { status: 405 })
}

Catch-all Routes

[...catch] handles unmatched /api/* paths. Catch-all values are available under params['*'] and under the folder name.

src/app/api/[...catch].ts
export default function handler(
  request: Request,
  { params }: { params: { '*': string } }
) {
  console.warn('Unmatched API route', {
    method: request.method,
    path: params['*'],
  })

  return Response.json(
    {
      error: 'Not Found',
      message: 'The requested endpoint does not exist',
    },
    { status: 404, headers: { 'Cache-Control': 'no-store' } }
  )
}

Environment Variables

Access environment variables directly from the env object in the request context. This ensures your code works across all deployment platforms.

src/app/api/config.ts
export default function handler(
  request: Request,
  { env }: { env: Record<string, string | undefined> }
) {
  const apiKey = env.MY_API_KEY
  const debug = env.DEBUG_MODE ?? 'false'
  const appName = env.APP_NAME ?? 'Bini.js'

  if (!apiKey) {
    return Response.json({ error: 'Missing MY_API_KEY' }, { status: 500 })
  }

  return Response.json({ appName, debug: debug === 'true', hasKey: !!apiKey })
}
On Node, env is backed by process.env. On edge platforms, it reads the runtime bindings.

Error Handling

Validate input and catch unexpected failures:

src/app/api/safe.ts
export default async function handler(
  request: Request,
  { env }: { env: Record<string, string | undefined> }
) {
  try {
    const body = await request.json()

    if (!body.email) {
      return Response.json({ error: 'Email is required' }, { status: 400 })
    }

    return Response.json({ success: true })
  } catch (error: any) {
    const isDev = env.NODE_ENV === 'development'
    return Response.json(
      {
        error: 'Internal Server Error',
        ...(isDev && { details: error.message }),
      },
      { status: 500 }
    )
  }
}

When to Use Plain Handlers

ScenarioRecommendation
Single endpoint with simple logicPlain handler
Quick prototypesPlain handler
Simple CRUDPlain handler
Method-based dispatch without branchingPlain handler (per-method exports)
Multiple endpoints in one fileUse Hono
Need middlewareUse Hono
Complex routingUse Hono
Large production API surfaceUse Hono
Start with plain handlers. Switch to Hono when you need middleware, nested routes, or larger organization.

API Routes Overview

Files under app/api/ map to /api/*.

Hono Integration

Build API routes with the Hono framework.

Dynamic API Routes

Path parameters and catch-all segments.

Environment Variables

Read secrets in your API routes.

Deployment

Deploy to Node, Vercel, Netlify, Cloudflare, or Deno.

Loaders

Fetch data before a route renders.

Was this helpful?
PreviousAPI Routes Overview
NextHono Integration

On this page

  • Overview
  • Basic Handler
  • Route Mapping
  • Request Context
  • Handling HTTP Methods
  • Per-Method Exports
  • Reading Request Data
  • Sending Responses
  • Dynamic Routes
  • Catch-all Routes
  • Environment Variables
  • Error Handling
  • When to Use Plain Handlers
Edit this page on GitHub

Plain Function Handlers

Simple API endpoints with a default-exported Request → Response function.

Overview

Plain function handlers are the simplest way to create API routes. Export a function from a file in src/app/api/ and it becomes an endpoint at /api/*. Ideal for single endpoints that do not need Hono middleware or nested routing.

File-based routing: src/app/api/hello.ts is served at /api/hello. There is no bare /api root route.

Basic Handler

Export a default function that receives a Request and a context object. The file path sets the route - the function name does not matter.

src/app/api/hello.ts
export default function handler(request: Request) {
  return Response.json({ message: 'hello', method: request.method })
}

This creates /api/hello and responds to all HTTP methods unless you branch on request.method.

Route Mapping

File structure maps directly to API paths:

app
api
ƒhello.ts
ƒusers.ts
posts
ƒindex.ts
ƒ[id].ts
ƒ[...catch].ts
/api/hello
/api/users
/api/posts
/api/posts/:id
/api/*
File PathAPI Route
src/app/api/hello.ts/api/hello
src/app/api/users.ts/api/users
src/app/api/posts/index.ts/api/posts
src/app/api/posts/[id].ts/api/posts/:id
src/app/api/[...catch].ts/api/*

Request Context

Every handler receives a second argument with the route context. Use it for path params, query parameters, and runtime env bindings.

FieldTypeDescription
paramsobjectDynamic route params (e.g. { id: "123" })
searchParamsURLSearchParamsQuery string parameters
envanyRuntime env bindings (or process.env on Node)
waitUntil?functionExtends the request lifetime for background work

Handling HTTP Methods

Branch on request.method for different verbs, or export per-method handlers (GET, POST, etc.) instead of a default function.

src/app/api/posts.ts
export default function handler(request: Request) {
  if (request.method === 'GET') {
    return Response.json({ posts: [] })
  }
  if (request.method === 'POST') {
    return Response.json({ message: 'Post created' }, { status: 201 })
  }
  if (request.method === 'PUT') {
    return Response.json({ message: 'Post updated' })
  }
  if (request.method === 'DELETE') {
    return Response.json({ message: 'Post deleted' })
  }
  return Response.json({ error: 'Method not allowed' }, { status: 405 })
}
MethodTypical Use
GETRetrieve data
POSTCreate new data
PUTReplace existing data
PATCHPartially update data
DELETERemove data

Per-Method Exports

Instead of one default function that branches on request.method, export a separate function for each HTTP verb. Each one is a plain function that receives the same Request and context object, and returns a Response.

src/app/api/posts.ts
export function GET(request: Request) {
  return Response.json({ posts: [] })
}

export async function POST(request: Request) {
  const body = await request.json()
  return Response.json({ message: 'Post created', body }, { status: 201 })
}

export function DELETE(request: Request) {
  return Response.json({ message: 'Post deleted' })
}

The context object is passed as the second argument, exactly like a default function:

src/app/api/posts/[id].ts
export function GET(
  request: Request,
  { params }: { params: { id: string } }
) {
  return Response.json({ id: params.id })
}
BehaviorDetails
Supported exportsGET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
Unhandled methodsReturn 405 with an Allow header
HEAD fallbackFalls back to GET when no HEAD export exists
PrecedenceMethod exports take precedence over a default export

Reading Request Data

Body, headers, and query params:

src/app/api/echo.ts
export default async function handler(request: Request) {
  const body = await request.json().catch(() => null)
  const userAgent = request.headers.get('User-Agent')
  const url = new URL(request.url)
  const page = url.searchParams.get('page')

  return Response.json({
    method: request.method,
    body,
    headers: { userAgent },
    query: { page },
  })
}

Sending Responses

Common response patterns:

src/app/api/responses.ts
export default function handler(request: Request) {
  // JSON
  return Response.json({ message: 'Hello JSON' })

  // Plain text
  // return new Response('Hello Text', {
  //   headers: { 'Content-Type': 'text/plain' },
  // })

  // Custom status
  // return Response.json({ message: 'Created' }, { status: 201 })

  // Redirect
  // return Response.redirect('https://example.com', 302)
}

Dynamic Routes

Path params are available in the context object, not a header. Use { params } as the second argument:

src/app/api/posts/[id].ts
export default function handler(
  request: Request,
  { params }: { params: { id: string } }
) {
  if (request.method === 'GET') {
    return Response.json({ id: params.id, title: `Post ${params.id}` })
  }

  return Response.json({ error: 'Method not allowed' }, { status: 405 })
}

Catch-all Routes

[...catch] handles unmatched /api/* paths. Catch-all values are available under params['*'] and under the folder name.

src/app/api/[...catch].ts
export default function handler(
  request: Request,
  { params }: { params: { '*': string } }
) {
  console.warn('Unmatched API route', {
    method: request.method,
    path: params['*'],
  })

  return Response.json(
    {
      error: 'Not Found',
      message: 'The requested endpoint does not exist',
    },
    { status: 404, headers: { 'Cache-Control': 'no-store' } }
  )
}

Environment Variables

Access environment variables directly from the env object in the request context. This ensures your code works across all deployment platforms.

src/app/api/config.ts
export default function handler(
  request: Request,
  { env }: { env: Record<string, string | undefined> }
) {
  const apiKey = env.MY_API_KEY
  const debug = env.DEBUG_MODE ?? 'false'
  const appName = env.APP_NAME ?? 'Bini.js'

  if (!apiKey) {
    return Response.json({ error: 'Missing MY_API_KEY' }, { status: 500 })
  }

  return Response.json({ appName, debug: debug === 'true', hasKey: !!apiKey })
}
On Node, env is backed by process.env. On edge platforms, it reads the runtime bindings.

Error Handling

Validate input and catch unexpected failures:

src/app/api/safe.ts
export default async function handler(
  request: Request,
  { env }: { env: Record<string, string | undefined> }
) {
  try {
    const body = await request.json()

    if (!body.email) {
      return Response.json({ error: 'Email is required' }, { status: 400 })
    }

    return Response.json({ success: true })
  } catch (error: any) {
    const isDev = env.NODE_ENV === 'development'
    return Response.json(
      {
        error: 'Internal Server Error',
        ...(isDev && { details: error.message }),
      },
      { status: 500 }
    )
  }
}

When to Use Plain Handlers

ScenarioRecommendation
Single endpoint with simple logicPlain handler
Quick prototypesPlain handler
Simple CRUDPlain handler
Method-based dispatch without branchingPlain handler (per-method exports)
Multiple endpoints in one fileUse Hono
Need middlewareUse Hono
Complex routingUse Hono
Large production API surfaceUse Hono
Start with plain handlers. Switch to Hono when you need middleware, nested routes, or larger organization.

API Routes Overview

Files under app/api/ map to /api/*.

Hono Integration

Build API routes with the Hono framework.

Dynamic API Routes

Path parameters and catch-all segments.

Environment Variables

Read secrets in your API routes.

Deployment

Deploy to Node, Vercel, Netlify, Cloudflare, or Deno.

Loaders

Fetch data before a route renders.

Was this helpful?
PreviousAPI Routes Overview
NextHono Integration

On this page

  • Overview
  • Basic Handler
  • Route Mapping
  • Request Context
  • Handling HTTP Methods
  • Per-Method Exports
  • Reading Request Data
  • Sending Responses
  • Dynamic Routes
  • Catch-all Routes
  • Environment Variables
  • Error Handling
  • When to Use Plain Handlers
Edit this page on GitHub