Learning material for professionals eager to explore the science behind building a successful online product

#ASKTHEINDUSTRY 27: Caching static assets in NodeJS: how and how long?

Talking about caching with front end developers is often like talking my dog into eating her food. She is hungry, she knows the needs it, but she still needs convincing. It smells worse than what we human eat and she would rather not eat her own food.

We front end developers tend to overthink when it comes to caching. We get scared of terrible terms such as LRU and LFU, and we often decide that we are better off avoiding caching entirely.

If that sounds anything like yourself, I’m here to tell you, my friend, that caching doesn’t need to be that complicated. In fact, it’s pretty straightforward.

I’ll cover a couple of aspects to keep in mind when implementing a caching mechanism, and then drop in the three-liner you need in order to enable caching in Node.

Let’s go:

  • The network is the devil. Caching is your best friend. It can’t be overstated, the network is the worst bottleneck for the Web and caching helps mitigating the problem! So, (wo)man up and do what’s necessary. In particular, I’d advice a (very) long max age. I usually use one year.
  • Implement this very simple naming system. It’s easily automatized and makes updating cached assets very simple.

That’s it. That’s all you need to know, as a front end developer. I’ll leave you with some code. In NodeJS (+ express), you can simply:

const express = require('express');

// Configure the path of your static assets
const path = 'path/to/your/assets';

// Provide the max age
const options = {
  maxAge: 31536000000 // One year

const app = express();

// Tell to express to cache 'em all
app.use( express.static(path, options) );

If you’ve found this post useful at all, press the ❤ button! I read each and every comment, so be sure to contribute to the conversation with your thoughts!

Care to leave a comment? Drop down a line on the Twitters