These integration guides are not official documentation and the Strapi Support Team will not provide assistance with them.
Why Use Redis
Redis is an open-source, in-memory data store with sub-millisecond response times, making it ideal for real-time analytics, session management, and caching. By integrating Redis with Strapi, you can efficiently handle various data structures—strings, hashes, lists, sets, and sorted sets—within your content management system.
Redis balances performance and reliability with data persistence using snapshots or append-only files. It offers a publish/subscribe model and supports Lua scripting for asynchronous processing, boosting your application's throughput. High availability and partitioning come standard through Redis Sentinel and Redis Cluster.
For more details, see the official Redis documentation.
Why Use Strapi?
Strapi is the leading open-source headless CMS offering features, like customizable APIs, role-based permissions, multilingual support, etc. It simplifies content management and integrates effortlessly with modern frontend frameworks.
Explore the Strapi documentation for more details.
Strapi 5 Highlights
The out-of-the-box Strapi features allow you to get up and running in no time: 1. Single types: Create one-off pages that have a unique content structure. 2. Draft and Publish: Reduce the risk of publishing errors and streamline collaboration. 3. 100% TypeScript Support: Enjoy type safety & easy maintainability 4. Customizable API: With Strapi, you can just hop in your code editor and edit the code to fit your API to your needs. 5. Integrations: Strapi supports integrations with Cloudinary, SendGrid, Algolia, and others. 6. Editor interface: The editor allows you to pull in dynamic blocks of content. 7. Authentication: Secure and authorize access to your API with JWT or providers. 8. RBAC: Help maximize operational efficiency, reduce dev team support work, and safeguard against unauthorized access or configuration modifications. 9. i18n: Manage content in multiple languages. Easily query the different locales through the API. 10. Plugins: Customize and extend Strapi using plugins.
Learn more about Strapi 5 feature.
See Strapi in action with an interactive demo
Setup Strapi 5 Headless CMS
We are going to start by setting up our Strapi 5 project with the following command:
🖐️ Note: make sure that you have created a new directory for your project.
You can find the full documentation for Strapi 5 here.
Install Strapi
npx create-strapi-app@latest server
You will be asked to choose if you would like to use Strapi Cloud we will choose to skip for now.
Strapi v5.6.0 🚀 Let's create your new project
We can't find any auth credentials in your Strapi config.
Create a free account on Strapi Cloud and benefit from:
- ✦ Blazing-fast ✦ deployment for your projects
- ✦ Exclusive ✦ access to resources to make your project successful
- An ✦ Awesome ✦ community and full enjoyment of Strapi's ecosystem
Start your 14-day free trial now!
? Please log in or sign up.
Login/Sign up
❯ Skip
After that, you will be asked how you would like to set up your project. We will choose the following options:
? Do you want to use the default database (sqlite) ? Yes
? Start with an example structure & data? Yes <-- make sure you say yes
? Start with Typescript? Yes
? Install dependencies with npm? Yes
? Initialize a git repository? Yes
Once everything is set up and all the dependencies are installed, you can start your Strapi server with the following command:
cd server
npm run develop
You will be greeted with the Admin Create Account screen.
Go ahead and create your first Strapi user. All of this is local so you can use whatever you want.
Once you have created your user, you will be redirected to the Strapi Dashboard screen.
Publish Article Entries
Since we created our app with the example data, you should be able to navigate to your Article collection and see the data that was created for us.
Now, let's make sure that all of the data is published. If not, you can select all items via the checkbox and then click the Publish button.
Enable API Access
Once all your articles are published, we will expose our Strapi API for the Articles Collection. This can be done in Settings -> Users & Permissions plugin -> Roles -> Public -> Article.
You should have find
and findOne
selected. If not, go ahead and select them.
Test API
Now, if we make a GET
request to http://localhost:1337/api/articles
, we should see the following data for our articles.
🖐️ Note: The article covers (images) are not returned. This is because the REST API by default does not populate any relations, media fields, components, or dynamic zones.. Learn more about REST API: Population & Field Selection.
So, let's get the article covers by using the populate=*
parameter: http://localhost:1337/api/articles?populate=*
Getting Started With Redis
Integrating Redis with Strapi improves performance by managing caching and background processes. After setting up Redis in your Strapi project, you might also consider how to deploy your Strapi project for production use. Here's how to set up the environment, adjust configurations, and implement the code to integrate Redis with Strapi.
Configuring the Strapi Environment for Redis Integration
Make sure you have a running Redis instance before you start coding. It could be a local installation, a Docker container, or a managed service like AWS ElastiCache. Update Strapi’s environment files with your Redis connection details, including REDIS_HOST
, REDIS_PORT
, and any necessary credentials, if you are configuring Redis for caching or other storage purposes. Following Strapi integration tips can ensure a smooth setup when incorporating services like Redis. Properly configuring your Redis connection is crucial for features like caching and rate limiting in Strapi. Strapi Cloud provides a pre-configured PostgreSQL database, so adding an external database is not necessary. However, you have the option to configure Strapi Cloud to use an external SQL database if specific performance or security needs arise. This involves setting up environment variables and ensuring the database schema aligns with your Strapi project. Keep in mind that using an external database may lead to increased network latency and potential security concerns, and Strapi cannot support external databases configured with Strapi Cloud.
Installing and Adjusting Settings for Redis in Strapi
Install Redis on your machine using a package manager or the method that fits your operating system. For Ubuntu:
sudo apt-get install redis-server
sudo service redis-server start
In your Strapi project, install the Node.js package needed to communicate with Redis:
npm install ioredis
To set up a Redis client in Strapi using the ioredis
library, create a configuration file with the following setup:
1const Redis = require('ioredis');
2
3module.exports = ({ env }) => ({
4 redis: {
5 client: new Redis({
6 host: env('REDIS_HOST', '127.0.0.1'),
7 port: env.int('REDIS_PORT', 6379),
8 password: env('REDIS_PASSWORD'),
9 }),
10 },
11});
Setting up Redis can help enhance productivity with Strapi. While setting up Redis, consider using Strapi security plugins to enhance your application's security. Ensure these plugins follow security guidelines, do not collect sensitive data improperly, are protected from common vulnerabilities, and have updated dependencies.
Code Implementation for Redis and Strapi Integration
One common use for integrating Redis with Strapi is caching. For more advanced caching strategies for Strapi, consider using plugins like REST Cache. Here's an example:
1const { redis } = require('./path/to/your/redisConfig');
2
3// Store data in cache
4redis.set('someKey', JSON.stringify(someData), 'EX', 3600);
5
6// Retrieve data from cache
7redis.get('someKey', (err, result) => {
8 if (err) {
9 console.error('Error fetching from Redis:', err);
10 } else {
11 const data = JSON.parse(result);
12 console.log('Fetched data:', data);
13 }
14});
Redis pairs effectively with the Bull library for handling queue-based tasks in Strapi:
1const Queue = require('bull');
2const queue = new Queue('strapiQueue', {
3 redis: {
4 host: process.env.REDIS_HOST,
5 port: process.env.REDIS_PORT,
6 password: process.env.REDIS_PASSWORD,
7 },
8});
9
10queue.process(async (job) => {
11 // Perform task logic
12});
13
14queue.add({ someTask: 'data' });
Redis can be used to build API request throttling mechanisms in a Strapi application, allowing control over user interactions by tracking request frequency and number per user. Additionally, Redis can function as a message broker for handling asynchronous tasks like email processing, enabling efficient background task management while keeping the application responsive.
Use a tool like bull-board to monitor your job queue. Explore Strapi's documentation and community resources for guidance on deploying and managing projects, including setting up caches and queues.
Set up Redis in Strapi as shown, and you'll experience faster response times, efficient scalability, and a solid backend foundation.
Awesome, great job!
Strapi Open Office Hours
If you have any questions about Strapi 5 or just would like to stop by and say hi, you can join us at Strapi's Discord Open Office Hours Monday through Friday at 12:30 pm - 1:30 pm CST: Strapi Discord Open Office Hours
For more details, visit the Strapi documentation and Redis documentation.