Redis middleware

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.

Install redis as a dependency:

Start by initializing a Redis client. Copy the following code into server.ts:

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:

  • req represents an HTTP request sent to the server.

  • res represents the response that will be sent by the server.

  • next is a reference to the next request handler.


This page is a preview of The newline Guide to Angular Universal

Start a new discussion. All notification go to the author.