In this lesson you will create a Node.JS middle-ware, that will be responsible for caching rendered views inside Redis database.
Implementing Redis Middleware#
It's time to implement the server logic to handle requests from the end user and check for rendered output in Redis. If an entry doesn't exist in the Redis database, then the rendering process is triggered, and the output is saved to the database.
redis as a dependency:
Start by initializing a Redis client. Copy the following code into
This code sets up the
redisUrl variable that depends on the
NODE_ENV environment variable. If the application runs in the development environment,
redisUrl is set to localhost. Otherwise, it is set to the Heroku instance URL. Then
redisClient is initialized, and all errors that might occur (such as if a Redis instance is not running) are handled.
Remember to replace the
redisUrl value with your Redis URI, obtained in previous lesson.
You can now implement Redis middleware:
This is a regular Node.js middleware function that accepts three parameters: