Most firms strive to retrieve and store data faster. It is because no one wants an application that lags. When there's a lot of data in the database, it becomes challenging to fetch data from the database swiftly, which may cause your application to lag. To avoid this, most software firms cache data.
Caching is the process of storing data in a temporary storage area so that retrieving data is relatively more accessible and faster.
The idea of caching aims to increase data retrieval performance by reducing the need to access the underlying slower storage layer. By trading off capacity for speed, a cache typically stores a subset of data transiently, in contrast to databases whose data are usually complete and durable.
Strapi REST Cache Plugin caches incoming GET
requests on the Strapi API based on query params and model ID. This plugin allows you to either cache your data on your application's memory with InMemory cache, with Redis, a third-party database or Couchbase cache. The cache is automatically busted every time a PUT
, POST
, or DELETE
request comes in.
This article will explore the Strapi REST Cache Plugin and how to cache data in our Strapi application.
Before you can jump into this content, you need to:
Just as I emphasized in my opening statement, time is of great essence when dealing with data. Most software store their data in a database, which may have different storage layers. Because of the different layers of storage in the database and how large the data is, it becomes difficult to retrieve data faster. Although users must have accessed the same information earlier, it doesn't get displayed more quickly when they re-access them.
To make fetching data easier, developers use a caching system. A caching system is a high-speed data storage layer, which stores a batch of data from the database. Whenever a user retrieves information from the database, the data is stored in a cache to increase data retrieval performance instead of accessing data from the different storage layers whenever a user requests them.
The cache doesn't contain all of the data in the database, just a fraction of the data. In most cases, data previously accessed by the users. Below are some importance of caching and why most software firms incorporate it into their application:
For the purpose of this article, we will be using a Strapi template. Run this command on your terminal to install nextjs blog strapi starter
npx create-strapi-starter my-project next-blog
This command creates two folders:
cd backend
yarn add strapi-plugin-rest-cache strapi-plugin-redis strapi-provider-rest-cache-redis
#or
npm install strapi-plugin-rest-cache strapi-plugin-redis strapi-provider-rest-cache-redis
strapi-plugin-rest-cache
This plugin provides a way to cache HTTP requests in order to improve performance. The cache content is stored by a provider, which can be either an in-memory provider, a redis connection, a file system, or any other custom provider.
strapi-plugin-redis
This is the universal redis connector we will need for our redis cache provider package. We will be using the LRU-based response cache for our REST API.
Briefly, let’s describe how an LRU based response cache works. This cache converts an API request, such as api.posts.get({ article: 'How to fix a bug '})
into two caches:
- A cache of ids returned by that particular query
- A global cache of data objects
The aim of this is that when you run api.posts.get({ id: 1 })
, and if the previous query had already populated a post
with id 1
, you will get an immediate response rather than making another server round-trip.
strapi-provider-rest-cache-redis
This provider package stores the cache content.
The strapi-plugin-rest-cache
provides us with three storage options for configuring caching with strapi. They are:
For the purpose of this post, we’ll be using the redis cache. We’ve already installed the plugin and the cache provider in the previous section. Before we move on to configure redis as the storage engine, make sure you install and start redis server using any of the links below:
Start your redis server with redis-server
, you should get something like this:
Redis default port is 6379
, we will use this in our configuration. Create a plugins.js
file in the config
folder and add these lines of code:
1 //config/plugin.js
2
3 module.exports = {
4 // Step 1: Configure the redis connection
5 // @see https://github.com/strapi-community/strapi-plugin-redis
6 redis: {
7 config: {
8 connections: {
9 default: {
10 connection: {
11 host: '127.0.0.1',
12 port: 6379,
13 db: 0,
14 },
15 settings: {
16 debug: false,
17 },
18 },
19 },
20 },
21 },
22 // Step 2: Configure the redis cache plugin
23 "rest-cache": {
24 config: {
25 provider: {
26 name: "redis",
27 options: {
28 max: 32767,
29 connection: "default",
30 },
31 },
32 strategy: {
33
34 enableEtagSupport: true,
35 logs: true,
36 clearRelatedCache: true,
37 maxAge: 3600000,
38 contentTypes: [
39 // list of Content-Types UID to cache
40 "api::category.category",
41 "api::article.article",
42 "api::global.global",
43 "api::homepage.homepage",
44 {
45 contentType: "api::category.category",
46 maxAge: 3600000,
47 hitpass: false,
48 keys: {
49 useQueryParams: false,
50 useHeaders: ["accept-encoding"],
51 },
52 maxAge: 18000,
53 method: "GET",
54 }
55 ],
56 },
57 },
58 },
59 };
Let’s break the code above to smaller chunks. Firstly, the plugins.js
handles the plugins we will be adding to our Strapi app.
1 module.exports = {
2 redis:{
3 config: {
4 connections: {
5 default: {
6 connection: {
7 host: '127.0.0.1',
8 port: 6379,
9 db: 0,
10 },
11 settings: {
12 debug: false,
13 },
14 },
15 },
16 },
17 }
18
19 }
Here, we configured the redis connection. We specified that our redis server is started at port 6379
and we also set debug
to false
, by default, it’s true.
1 "rest-cache": {
2 config: {
3 provider: {
4 name: "redis",
5 options: {
6 max: 32767,
7 connection: "default",
8 },
9 },
10 }
Here, we are configuring the rest-cache
. We start by specifying that redis is going to be the storage engine and we set max
to 32767
. Max denotes the maximum number of entries that the cache can take in. By default, this number is set to 32767.
1 strategy: {
2 enableEtagSupport: true,
3 logs: true,
4 clearRelatedCache: true,
5 maxAge: 3600000,
6 contentTypes: [
7 "api::category.category",
8 "api::article.article",
9 "api::global.global",
10 "api::homepage.homepage",
11 ],
12 },
Here, we went on to specify some extra settings using the rest-cache
strategy
object. Let’s go through what each of these settings do.
The maxAge
tells us the time after which a cache entry will be considered invalid. This time is usually represented in milliseconds. The default maxAge
in the strapi-plugin-rest-cache
is 3600000 milliseconds.
Etag (entity tag) headers are identifiers for a specific version of data. ETags prevents updates of a resource that could be simultaneous from overwriting each other. By default, the property enableEtagSupport
is set to false.
strapi-plugin-rest-cache
logs output in your console. For instance, when we first ran our project after configuring the middleware, we got the output below.
By default, the property log
is set to true
. If you set the property to false
, you won't get an output in your console concerning the plugin.
As the name suggests, it clears related cache content from memory. By default, it’s set to false.
These are the Strapi content types we are configuring. All the settings above will be applied to these content types.
You can configure the properties of each content type individually. For developers with a lot of content types, this is always helpful.
For instance, you'll want to configure the maxAge
property individually since the content types will be accessing different types of resources. To configure content types properties individually, put the property of interest into the content type property as shown below.
1 contentTypes: [
2 // list of Content-Types UID to cache
3 "api::category.category",
4 "api::article.article",
5 "api::global.global",
6 "api::homepage.homepage",
7 {
8 contentType: "api::category.category",
9 hitpass: false,
10 keys: {
11 useQueryParams: false,
12 useHeaders: ["accept-encoding"],
13 },
14 maxAge: 18000,
15 method: "GET",
16 }
17 ],
Here, we modified the maxAge
for the category
content type and added some more properties. Now, go ahead and start the strapi development server with
yarn develop --watch-admin
#or
npm run develop --watch-admin
Sign up or log in to the Strapi admin and head to plugins. You will see that our plugins were installed successfully
Then, navigate to the Content Manager tab and you will be presented with a screen like this:
A Purge REST Cache
button has appeared! This enables you to clear the cache from the admin dashboard.
The Strapi plugin rest cache was designed for public route casing. If a private route with authorization header is connected to the cache, public users can access the route without authentication and they won’t be asked for bearer token. This is because the cache runs before the user-permissions plugin; hence, the route’s content is cached without authentication.
In this article, we have explored caching in Strapi with the strapi-plugin-rest cache. We first discussed caching and why it is necessary to add caching to your application. Next, we looked at the strapi-plugin-rest cache and installed and set it up in our working environment. Then we explored the different configurations and properties for the strapi-plugin-rest cache.
Software Engineer focused on building web applications and writing technical content.