Caching your views with Redis using the Express Framework

Hi again! On this post, I will show how to use the express-redis-cache package to cache your views, decreasing your page load.

The package is very simple to use, but he is also very complete. I am using it on this blog, and am not missing any important feature. It’s also very efficient, because it uses Redis to store the cache.

Installing and Configuring

To install, include express-redis-cache to your package.json dependencies, or type

I will assume that you are using the 0.1.8 version, which is the most recent at this moment.

So, we must specify the basic configurations of the package.

The prefix option is used to construct the strings that will identify each one of the cached pages. The app object is exported like a module, so we can use the same cache object in other files, with the same Redis connection.

If you is already conected to a Redis server, you can use the option {client : redis_client_object}, omitting host, port and auth_pass. If your Redis server require a password, you need to authenticate the redis client by yourself.

Basic Usage

The cache.route() middleware must be used on every route that should be cached.

This will ask to cache to check if there is some cache named APP_ NAME + '/'. If not, thehome() function will be executed, and ‘Welcome to my app’ will be automatically cached, with the APP_NAME + '/' name. While it doesn’t expire, the home() function will no longer be called.

Changing the Entries Name

You can change the name of a entry using

or

or

Choosing to Cache (or not) a Page

You can chose not to use the cached answer on the fly.

Ovewriting the expire option

To change the expiration time of a single entry, do

Excluding Cache Entries

You can exclude cache entries, even if they haven’t expired yet.

If you have pagination at your homepage, with each page saved on entries like home.page.0,home.page.1, and so on, you can exclude all these entries with a single call to del() function.

Debugging

To listen the various debug messages sent by the package,

In medium/large applications, your page load will decrease considerably if you cache your views. However, you must be careful to clear the cache whenever your views are updated. You don’t want an old HTML including a updated javascript, do you?

Leave a Reply

Your email address will not be published. Required fields are marked *