nitrojs / nitro

Next Generation Server Toolkit. Create web servers with everything you need and deploy them wherever you prefer.
https://nitro.build
MIT License
6.16k stars 507 forks source link

feat(renderer): add `render:before` hook #2770

Closed pi0 closed 1 month ago

pi0 commented 1 month ago

(context: Discussion with @atinux regarding how to set cache callback options to the renderer handler. This PR, adds a primitive to allow it with advanced usage)


This PR adds a new render:before runtime hook support for renderer handlers (like Nuxt SSR). This hook allows to customize rendering behavior by intercepting the context:

Usage is not restricted to caching only and it allows more general customization of renderer behavior but for particularly caching purposes here is an example:

import { defineNitroPlugin, defineCachedFunction } from "nitro/runtime";

export default defineNitroPlugin((nitro) => {
  const cache = new WeakMap();
  nitro.hooks.hook("render:before", (ctx) => {
    let render = cache.get(ctx.render);
    if (!render) {
      render = defineCachedFunction(ctx.render, {
        // Custom cache options
        maxAge: 60_000,
        shouldBypassCache: (event) => { /* custom logic */ }
      });
      cache.set(ctx.render, render);
    }
    ctx.render = render;
  });
});