The author selected /dev/color to receive a donation as part of the Write for DOnations program.
Introduction
Most applications depend on data, whether it comes from a database or an API. Fetching data from an API sends a network request to the API server and returns the data as the response. These round trips take time and can increase your application response time to users. Furthermore, most APIs limit the number of requests they can serve an application within a specific time frame, a process known as rate limiting.
To get around these problems, you can cache your data so that the application makes a single request to an API, and all the subsequent data requests will retrieve the data from the cache. Redis, an in-memory database that stores data in the server memory, is a popular tool to cache data. You can connect to Redis in Node.js using the node-redis module, which gives you methods to retrieve and store data in Redis.
In this tutorial, you’ll build an Express application that retrieves data from a RESTful API using the axios module. Next, you will modify the app to store the data fetched from the API in Redis using the node-redis module. After that, you will implement the cache validity period so that the cache can expire after a certain amount of time has passed. Finally, you will use the Express middleware to cache data.
Prerequisites
To follow the tutorial, you will need:
-
Node.js environment setup on your server. If you are on Ubuntu 22.04, install the latest version of Node.js and npm by following option 3 in How To Install Node.js on Ubuntu 22.04. For other operating systems, see the How to Install Node.js and Create a Local Development Environment series.
-
Redis installed on your server. If you’re using Ubuntu 22.04, follow steps 1 and 2 of How To Install and Secure Redis on Ubuntu 22.04. If you’re working on another operating system, see How to Install and Secure Redis.
-
Knowledge of asynchronous programming. Follow Understanding the Event Loop, Callbacks, Promises, and Async/Await in JavaScript.
-
Basic knowledge using the Express web framework. See How To Get Started with Node.js and Express.
Step 1 — Setting Up the Project
In this step, you’ll install the dependencies necessary for this project and start an Express server. In this tutorial, you’ll create a wiki containing information about different kinds of fish. We’ll call the project fish_wiki.
First, create the directory for the project using the mkdir command:
- mkdir fish_wiki
Move into the directory:
- cd fish_wiki
Initialize the package.json file using the npm command:
- npm init -y
The -y option accepts all defaults automatically.
When you run the npm init command, it will create the package.json file in your directory with the following contents:
OutputWrote to /home/your_username/^fish_wiki^/package.json:{ "name": "fish_wiki", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo "Error: no test specified"" exit 1"" }