Skip to main content

Express.js Caching Techniques: Speed Up Your App

Building fast, efficient web applications is more important than ever. If you're using Express.js, you're probably focused on delivering pages super fast. Yet, have you thought about caching strategies? Caching can be the secret sauce to make your app lightning quick. Don't know where to start? No worries, we've got you covered.

Why Caching Matters in Express.js

Imagine this: every time a user visits your app, the server processes the same data again and again. Don't you think that's a waste of resources? That's where caching comes in. Caching stores a copy of the data so it can be served up quickly, reducing server load and improving response times.

Types of Caching

There are several caching techniques to consider. Each has its unique pros and cons. Let's explore:

  • In-memory Caching: Stores data in memory. Quick access but limited by RAM.
  • File-based Caching: Saves cached data into files. Slower than memory-based caching but more persistent.
  • Distributed Caching: Utilizes external resources like Redis or Memcached. Great for scaling across multiple instances.

Implementing In-memory Caching with Node-cache

Say you want to stick with in-memory caching because it's simple for your use case. Node-cache is a popular choice. It acts like a simple key-value store for your cached data.

Installing Node-cache

First thing first, you need to install it. Open your terminal and enter:

npm install node-cache

Basic Implementation

Let's dive into a basic setup. Imagine you want to cache user data for a brief period.

const NodeCache = require("node-cache");
const myCache = new NodeCache({ stdTTL: 100, checkperiod: 120 });

// Caching data
myCache.set("user_123", { name: "John", age: 30 });

// Fetching cached data
const user = myCache.get("user_123");

if (user) {
  console.log(user); // { name: "John", age: 30 }
} else {
  // Fetch from database as fallback
}

Code Breakdown

  • Instantiation: new NodeCache({ stdTTL: 100, checkperiod: 120 }) sets default Time-To-Live (TTL) for cached items to 100 seconds. checkperiod automates cache cleanup every 120 seconds.
  • Setting Data: myCache.set("user_123", ...) saves user data with a unique key.
  • Getting Data: myCache.get("user_123") retrieves the data if available. If not, you can resort to fetching from your DB.

Using Redis for Distributed Caching

Redis helps share cache across multiple app instances. You won't have to worry about inconsistent data when scaling out.

Installing Redis

First, you need Redis installed on your machine. Visit the Redis website for installation instructions.

Once Redis is up, install the redis package for Node.js:

npm install redis

Setting Up Redis Cache

Here's how you can use Redis in your Express app:

const redis = require('redis');
const client = redis.createClient();

// Connect to Redis
client.on('connect', () => {
  console.log('Connected to Redis');
});

// Caching response
app.get('/data', (req, res) => {
  const key = 'data_key';

  client.get(key, (err, data) => {
    if (err) throw err;

    if (data) {
      res.send(JSON.parse(data));
    } else {
      // Fetch from a slow API or database
      const fetchedData = { message: "Hello, Redis!" };
      
      client.setex(key, 3600, JSON.stringify(fetchedData));
      res.send(fetchedData);
    }
  });
});

Code Breakdown

  • Redis Client: redis.createClient() connects your app to Redis.
  • Data Retrieval: client.get(key, ...) checks Redis for existing cached data.
  • Setting Data: If data isn't cached, it fetches fresh data and saves it using client.setex(key, 3600, ...), setting an expiry of one hour (3600 seconds).

Conclusion

Getting caching right can be transformative for your Express.js app. Whether it's simple in-memory caching for fewer users or scalable solutions with Redis, the benefits are clear. Faster responses and happier users. So, next time your app feels sluggish, think caching. It's a game of milliseconds in the app world, and caching might just give you the edge.

Still have questions? Ask yourself: is your app as fast as it could be? If there's doubt, caching might be the key you've been missing. Dive in and experiment—your app's performance will thank you.

Popular posts from this blog

How to Check if Someone is Connected to Your Machine in Linux

Picture this: you glance at your system monitor and notice your CPU is humming along even though you're not running anything demanding. Or maybe your internet feels sluggish for no obvious reason. A small, uneasy thought creeps in — is someone else on my machine right now? For Linux users, this isn't something you have to wonder about. Linux ships with a powerful set of built-in tools that let you see exactly who's connected, who's logged in, and what your network is doing at any given moment. You don't need to be a security expert to use them — you just need to know where to look. This guide walks you through the practical, no-nonsense steps to check for unauthorized connections on your Linux system, with real commands you can run right now. Why Monitoring Network Connections Matters Every device on a network — including your own Linux machine — communicates using an IP address. When another device or user connects to your system, that connection shows up as a trac...

How to Set Up a Linux Web Server and Host an HTML Page Easily

Setting up a web server on Linux means spending a fair amount of time in the terminal — Linux leans heavily on the command line rather than clicking through menus, so you'll be typing out instructions more often than not.  If you're new to this, it can feel a little intimidating at first, but the good news is you don't need to become a Linux wizard overnight. A handful of core commands will get you surprisingly far. A few you'll lean on constantly: cd — move between directories ls — see what's in the current directory mkdir — create a new folder nano or vim — edit files right there in the terminal sudo — run something with administrator privileges Get comfortable with these and you'll be able to navigate around, tweak configuration files, and install software without much trouble. You don't need to memorize everything — you just need to be confident enough to follow along with clear instructions, which is exactly what this guide aims to give you....

C++ vcpkg Manifest Mode + CMake

 If you've ever tried to install a C++ library and felt like you were assembling furniture without instructions, this article is for you. We're going to talk about vcpkg manifest mode and how it works with CMake , and I'm going to explain it like you're five years old (in a good way — no judgment here). First, Let's Talk About the Problem In most programming languages, adding a library is easy. Python has pip install requests . JavaScript has npm install express . You type one command, and boom, the library shows up in your project. C++ never really had that. For decades, if you wanted to use a library like fmt or nlohmann/json , you had to: Download the source code yourself Figure out how to compile it Tell your compiler where to find the headers Tell your linker where to find the compiled binaries Cry a little vcpkg is Microsoft's answer to this mess. It's a package manager for C++ — like pip or npm , but for C++ libraries. And manifest mode...