question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Redis instance is being mapped only once per app visit and only to the page that is being hit

See original GitHub issue

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

Reproducible demo/repo here

I am mapping my redis instance to req.raw, but for some reason, it doesn’t persist through page navigations, even if you return to the same page.

In my afterHandler, I’m doing the following:

fastify.next('/', (app, req, reply) => {
	req.raw.redisInstance = fastify.redis;
	app.render(req.raw, reply.raw, '/', req.query);
});

fastify.next('/another', (app, req, reply) => {
	req.raw.redisInstance = fastify.redis;
	app.render(req.raw, reply.raw, '/another', req.query);
});

If you visit the index file or the another route, then the redis instance will be available the first time. The redis instance is also available if you refresh the page.

However if you first first index, then go to another, and then go back to index, the reference to the redis instance is lost.

I’ve tried doing as was suggested here, but to no avail.

What am I doing wrong here?

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:11 (8 by maintainers)

github_iconTop GitHub Comments

3reactions
radomirdcommented, Oct 8, 2021

After looking into the suggestion that @climba03003 proposed, I’ve realised that there could be a very easy solution to this issue which doesn’t require a change in the plugin.

@mkhoussid: In order to achieve to have the redis instance on all of the requests you could simply just add a onRequest hook and move the logic from your afterHandler to the hook and that will solve the problem.

fastify.addHook("onRequest", (req, reply, done) => {
  req.raw.redisInstance = fastify.redis;
  done();
});

Here is the full code (from your example):

server.js:

const fastifyConstructor = require("fastify");
const nextJs = require("fastify-nextjs");

const PORT = process.env.PORT || 3000;
const isDev = process.env.NODE_ENV !== "production";

const { registerPlugins, afterHandler, listenHandler } = require("./utils");

console.log("Environment: ", process.env.NODE_ENV);
const fastify = fastifyConstructor({
  // logger: isDev,
});

registerPlugins(fastify, isDev);

fastify.register(nextJs, { dev: isDev }).after(afterHandler(fastify, isDev));

fastify.addHook("onRequest", (req, reply, done) => {
  req.raw.redisInstance = fastify.redis;
  done();
});

fastify.listen(PORT, "::", listenHandler(PORT));

afterHandler.js

module.exports = (fastify) =>
  async function () {
    try {
      fastify.next('/');
      fastify.next('/another');
    } catch (err) {
      console.log('Error caught in afterHandler', err);
    }
};
1reaction
mkhoussidcommented, Oct 8, 2021

After looking into the suggestion that @climba03003 proposed, I’ve realised that there could be a very easy solution to this issue which doesn’t require a change in the plugin.

@mkhoussid: In order to achieve to have the redis instance on all of the requests you could simply just add a onRequest hook and move the logic from your afterHandler to the hook and that will solve the problem.

fastify.addHook("onRequest", (req, reply, done) => {
  req.raw.redisInstance = fastify.redis;
  done();
});

Here is the full code (from your example):

server.js:

const fastifyConstructor = require("fastify");
const nextJs = require("fastify-nextjs");

const PORT = process.env.PORT || 3000;
const isDev = process.env.NODE_ENV !== "production";

const { registerPlugins, afterHandler, listenHandler } = require("./utils");

console.log("Environment: ", process.env.NODE_ENV);
const fastify = fastifyConstructor({
  // logger: isDev,
});

registerPlugins(fastify, isDev);

fastify.register(nextJs, { dev: isDev }).after(afterHandler(fastify, isDev));

fastify.addHook("onRequest", (req, reply, done) => {
  req.raw.redisInstance = fastify.redis;
  done();
});

fastify.listen(PORT, "::", listenHandler(PORT));

afterHandler.js

module.exports = (fastify) =>
  async function () {
    try {
      fastify.next('/');
      fastify.next('/another');
    } catch (err) {
      console.log('Error caught in afterHandler', err);
    }
};

Yes, using hooks is also a valid approach. It needs to be tested and documented.

@radomird Could you send a PR for the test-case and documentation?

Works.

Sorry @radomird , docs are great, but writing them sucks.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Diagnosing latency issues - Redis
Enable and use the Latency monitor feature of Redis in order to get a human readable description of the latency events and causes...
Read more >
How to Monitor Redis Performance Metrics - Datadog
Metric to watch: hit rate. When using Redis as a cache, monitoring the cache hit rate can tell you if your cache is...
Read more >
Redis-specific parameters - Amazon ElastiCache for Redis
cluster.on – Use this parameter group, or one derived from it, for Redis (cluster mode enabled) clusters and replication groups.
Read more >
Connect to a Redis instance - Memorystore - Google Cloud
If you don't already have a Compute Engine VM that uses that same authorized network as your Redis instance, create one and connect...
Read more >
Moodle in English: Moodle performance during ... - Moodle.org
Visiting notification page is purging all opcache and overwriting muc/config. ... I could only suggest to create two different Redis instances, one for...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found