Plugins

Extend Fumapress via plugins.

Overview

Plugins allow you to customize Fumapress and encapsulate the complexity into a plugin.

my-plugin.tsx
import type { AppShape, PressPlugin } from "fumapress";

export function myPlugin<C extends AppShape = AppShape>(): PressPlugin<C> {
  return {
    init() {
      // access internal hooks
      this.data["core:docs-layout"] ??= {};
      const transformers = (this.data["core:docs-layout"].transformers ??= []);
      transformers.push(({ data }) => {
        // add element below page body
        data.body = (
          <>
            {data.body}
            <div>Hello World</div>
          </>
        );
        return data;
      });
    },
    createPages({ createApi }) {
      // customize router
      createApi({
        path: "/api/hello-world",
        render: "dynamic",
        handlers: {
          POST: async (req) => {
            console.log(req);
            return new Response("I love Fumapress");
          },
        },
      });
    },
  };
}

Middlewares

Plugins can add Hono middlewares with createMiddlewares(), which run before routes on the server. For example, redirecting legacy URLs:

my-plugin.tsx
import type { AppShape, PressPlugin } from "fumapress";

export function redirectsPlugin<C extends AppShape = AppShape>(
  redirects: Record<string, string>,
): PressPlugin<C> {
  return {
    name: "redirects",
    createMiddlewares() {
      return [
        async (c, next) => {
          const to = redirects[c.req.path];
          if (to) return c.redirect(to, 308);

          return next();
        },
      ];
    },
  };
}

Middlewares require a server, they don't apply to a static deployment.

Last updated on

On this page