Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Add Redis request caching to Node.js with Express.js.
var zlib = require('zlib');
var redis = require('redis');
var redisClient = redis.createClient();
var crypto = require('crypto');
// Our custom caching write function
function cached(body, lifetime, type) {
var key = this.req.originalUrl;
var res = this;
var etag, len;
if (typeof body === 'object') {
body = JSON.stringify(body);
zlib.gzip(body, function(err, result) {
if (err) return;
len = result.length;
etag = crypto.createHash('md5').update(result).digest('hex');
// Send the result to the client first
res.setHeader('ETag', etag);
res.setHeader('Cache-Control', 'max-age=' + lifetime);
res.setHeader('Content-Encoding', 'gzip');
res.setHeader('Content-Length', len);
res.setHeader('Content-Type', type);
res.end(result, 'binary');
// Add the result to the Redis cache
var hash = {
etag: etag,
max_age: lifetime,
content_type: type,
content_length: len,
content_encoding: 'gzip'
redisClient.hmset(key + '-meta', hash, redis.print);
redisClient.set(key + '-content', result, redis.print);
redisClient.expire(key + '-meta', lifetime);
redisClient.expire(key + '-content', lifetime);
// Now configure Express to know about the caching function
var express = require('express');
var response = express.response;
response.cached = cached;
// An example of using this for a request, 300 being the number of seconds that Redis will keep it for.
function someRoute(req, res) {
var content = "blah, blah, blah";
res.cached(content, 300, 'text/html');

This comment has been minimized.

Copy link

mhdatie commented Oct 4, 2014

is this guaranteed? I'm trying to cache tweet results and the script looks neat and globally accessible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.