Generate Dummy Data in Strapi
How to seed data in Strapi using faker.js
- github: andriishupta/strapi-generate-seed-data
- Strapi's video with a general idea of how to "Generate dummy data"
📰 Also published on
Strapi is powerful open-source headless CMS that helps projects control code customization with extensibility and, at the same time, don't worry about implementing a full-blown Content Management System on their own.
So, after you have set up your Strapi, you want to build Front-End on top of it. You hire front-end developers who are stuck: "Ye, I can query for data via REST and GraphQL, but what data should I see? Could I have an example?"
To avoid this, we would generate example data upfront.
🌱 How to seed data?
"Generate dummy data"
There is the video in Strapi's Video-library that gave me a direction on how to do it.
The idea is simple:
- use Entity Service API for interactions
- generate dummy data with @faker-js/faker
Your case 💯 would be more complicated, so don't forget that you could take almost everything from Strapi's source code.
- find a place on Strapi Admin you want to copy
- check URL and Network(in developer's inspection) to understand what is called
- find code(start with controller) that corresponds to that calls
We have a simple Todo application(duh) with a Todo collection and a Todo List as a page(single type) that we want to send to the front-end. Also, our Todos has media functionality, so we upload some.
In the bootstrap function, we check for the development environment and decide if we should run seeding or not. Seeding would automatically run on the very first application run(valid when a developer clones an existing repository) and could be re-run with
yarn seed to force seed, which clears old and creates new data -
To create a todo using Entity Service API, we need to call the
create method with data that matches our entity. In the current example and during seeding, I have used "bulk promises" to run requests in parallel cause they are not dependent on each other.
And using faker, we fill a todo like this:
Fulfilling the "Todo List page" is the same as Collection, but keep in mind that it could be only one entry all the time. Also, it contains a Todo relation, so we get five todos to fill it.
To attach media on a todo, we first need to upload that media and then link its id to the entity. Code has been copied from Strapi's source code, modified, and I just created a helper function.
Example in Todo:
After opening the Admin panel, you will see generated data.
Thanks for reading!