fastify / fastify-nextjs

React server side rendering support for Fastify with Next
Other
526 stars 60 forks source link

How to implement ssr cache in next.js 13 #823

Closed SouthLink closed 10 months ago

SouthLink commented 10 months ago

Prerequisites

Issue

I learned about caching SSRS via fastify and @fastify/nextjs from this post, but this example doesn't work in Nex.js 13.2.0+, How To Avoid SSR Load Issues in Node.js

function spyOnEnd(chunk) {
  console.log(chunk);
  this.redis.set(this.req.url, chunk, "ex", 60);
  this.end.call(this.reply.raw, chunk);
}

async function main() {
  const redis = new Redis.Cluster(redisConfig[next_env]);

  await fastify.register(fastifyRedis, { client: redis, closeClient: true });

  fastify.addHook("onRequest", async (req, reply) => {
    console.log(req.url);
    // if (req.url !== "/m") {
    //   return;
    // }

    const cached = await fastify.redis.get(req.url);

    console.log(cached);

    reply.header("X-Build-Id", buildId);
    reply.header("X-Server-Env", next_env);

    if (cached) {
      console.log("Sending cached for", req.url);
      reply.header("X-SSR-Cache", "HIT");
      reply.type("text/html");
      reply.send(cached);
    } else {
      reply.header("X-SSR-Cache", "MISS");
      reply.raw.end = spyOnEnd.bind({
        req,
        reply,
        redis: fastify.redis,
        end: reply.raw.end,
      });
    }
  });
  await fastify.register(fastifyNext, {
    dev,
  });
  fastify.next("/*");
  await fastify.listen({ port });

  console.log(`> Server listening at http://localhost:${port} as ${dev ? "development" : process.env.NODE_ENV}`);
}

main();

From the above code, I can't get chunk in the spyOnEnd method, what can I do to successfully run the ssr cache example

SouthLink commented 10 months ago

Already solved, I used renderToHTML