Skip to content

API Handler

In keiro api handlers are functions exported from files under your routes directory, we recommend using the helper defineHandler for creating routes.

API Reference

API handlers take 2 arguments:

  • RequestEvent: Contains the request, url, params, cookies and request locals.
  • Next: A function that call the next route, on api handlers the next route is always the 404 handler.

And must return a Response object.

Handlers can be defined in any of these ways:

  1. Declaring a function.

    import type { RequestEvent, Next } from "keiro/types";
    export default function handler(event: RequestEvent, next: Next) {
    return new Response("Hello there!");
    }
  2. Using the defineHandler helper.

    import { defineMiddleware } from "keiro";
    export default defineHandler((event, next) => {
    return new Response("Hello there!");
    })
  3. Using the RequestHandler type.

    import type { RequestHandler } from "keiro/types";
    export default ((event, next) => {
    return new Response("Hello World");
    }) satisfies RequestHandler;

Catch-all methods

If you return a export default function it will be called on any http method:

src/routes/posts/index.ts
import { defineHandler } from "keiro";
export default defineHandler(() => {
return new Response("Posts page");
});

HTTP Method

You can return functions named: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, each will be called on that method.

src/routes/posts/index.ts
import { defineHandler } from "keiro";
export const GET = defineHandler(() => {
return new Response("Get posts");
});
export const POST = defineHandler(() => {
return new Response("Create post");
});
export const PUT = defineHandler(() => {
return new Response("Update post");
});
export const DELETE = defineHandler(() => {
return new Response("Delete post");
});
export default defineHandler(() => {
return new Response("Posts");
});

The named methods have priority over the export default, the rest will be handled by it.