Table of Contents


In Express.js you can use the standard memjs interface to get and set values as described in our Node.js documentation to cache expensive computations or database queries:

In addition there are two Express.js specific ways to use Memcache:

  1. Cache rendered views
  2. Store sessions

Cache rendered views

To cache rendered views it is best to create an Express.js middleware function as such:

If you use the cacheView middleware you need to take care to invalidate the cache whenever the view needs to be re-rendered, e.g., when the content changes. This can be done by deleting the cached item:

Storing Sessions in Memcache

Memcache works well for sessions that time out, however, since Memcache is a cache and thus not persistent, saving long-lived sessions in Memcache might not be ideal. For long-lived sessions consider a permanent storage option such as your database.

To use sessions in Express you need express-session and to store them in Memcache you need connect-memjs:

$ npm install express-session connect-memjs

Then you can configure sessions in your app: