Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 4 commits into from
Oct 2, 2024
Merged

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

merged 4 commits into from
Oct 2, 2024

Conversation

pi0
Copy link
Member

@pi0 pi0 commented Oct 2, 2024

(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:

  • Render function can be overridden or wrapped by setting context.render
  • A response can be directly generated/handled by setting context.response

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;
  });
});

@pi0 pi0 self-assigned this Oct 2, 2024
@pi0 pi0 merged commit d788218 into v2 Oct 2, 2024
5 checks passed
@pi0 pi0 deleted the feat/render-hook branch October 2, 2024 14:48
pi0 added a commit that referenced this pull request Oct 18, 2024
@pi0 pi0 mentioned this pull request Oct 31, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant