Learn how to set the default "populate" options via route middleware. Instead of passing "populate" on each request from the frontend, the can handle this functionality via route-based middleware in the backend. This will allow you to keep your frontend requests lean and organized.
You can also use this to control what data will be returned by default and not allow the user to add additional populate options in the frontend.
In Strapi, Route Middleware has a more limited scope and is configured and used as middleware at the route level. You can learn more in the Strapi documentation. Now, let's jump in and learn how to set this up.
In this example, I will use a simple blog post type consisting of a title, body, hero image, slug, and authors, which is a one-to-many relationship with a user. Each blog post can have many authors.
Before getting into how to implement custom middleware, let's look at why you might want to add middleware for this use case in the first place.
By default, population structure needs to be defined and sent on each client-side
request, else the request will return only top-level parent content.
A GET
request to localhost:1337/api/blog-posts
returns the following:
1// localhost:1337/api/blog-posts
2{
3 "data": [
4 {
5 "id": 1,
6 "attributes": {
7 "title": "Test Blog Post",
8 "body": "Test blog content",
9 "slug": "test-blog-post",
10 "createdAt": "2022-08-09T18:45:19.012Z",
11 "updatedAt": "2022-08-09T18:45:21.710Z",
12 "publishedAt": "2022-08-09T18:45:21.707Z"
13 }
14 }
15 ],
16 "meta": {
17 "pagination": {
18 "page": 1,
19 "pageSize": 25,
20 "pageCount": 1,
21 "total": 1
22 }
23 }
24}
This is not ideal, seeing as important data has been excluded, such as the heroImage
and authors
' information.
An easy solution to the problem above involves adding populate=*
to the initial query.
localhost:1337/api/blog-posts?populate=*
returns the following:
1// localhost:1337/api/blog-posts?populate=*
2{
3 "data": [
4 {
5 "id": 1,
6 "attributes": {
7 "title": "Test Blog Post",
8 "body": "Test blog content",
9 "slug": "test-blog-post",
10 "createdAt": "2022-08-09T18:45:19.012Z",
11 "updatedAt": "2022-08-09T19:22:39.637Z",
12 "publishedAt": "2022-08-09T18:45:21.707Z",
13 "heroImage": {
14 "data": {
15 "id": 1,
16 "attributes": {
17 "name": "test_cat.jpeg",
18 "alternativeText": "test_cat.jpeg",
19 "caption": "test_cat.jpeg",
20 "width": 500,
21 "height": 500,
22 "formats": {
23 "thumbnail": {
24 "name": "thumbnail_test_cat.jpeg",
25 "hash": "thumbnail_test_cat_2bdaa9fbe9",
26 "ext": ".jpeg",
27 "mime": "image/jpeg",
28 "path": null,
29 "width": 156,
30 "height": 156,
31 "size": 5.01,
32 "url": "/uploads/thumbnail_test_cat_2bdaa9fbe9.jpeg"
33 }
34 },
35 "hash": "test_cat_2bdaa9fbe9",
36 "ext": ".jpeg",
37 "mime": "image/jpeg",
38 "size": 21.78,
39 "url": "/uploads/test_cat_2bdaa9fbe9.jpeg",
40 "previewUrl": null,
41 "provider": "local",
42 "provider_metadata": null,
43 "createdAt": "2022-08-09T19:06:25.220Z",
44 "updatedAt": "2022-08-09T19:06:25.220Z"
45 }
46 }
47 },
48 "authors": {
49 "data": {
50 "id": 1,
51 "attributes": {
52 "username": "testUser",
53 "email": "test@test.com",
54 "provider": "local",
55 "confirmed": true,
56 "blocked": false,
57 "createdAt": "2022-08-09T19:07:03.325Z",
58 "updatedAt": "2022-08-09T19:07:03.325Z"
59 }
60 }
61 }
62 }
63 }
64 ],
65 "meta": {
66 "pagination": {
67 "page": 1,
68 "pageSize": 25,
69 "pageCount": 1,
70 "total": 1
71 }
72 }
73}
While this does return more data, the main flaw with this approach is that you don't have control over what data is returned. You are still not receiving valuable information, such as the author's role
while also receiving data you might not care about.
Instead of using populate=*
, you can filter the query using LHS Bracket syntax.
The query might look like this:
1localhost:1337/api/blog-posts?populate[heroImage][fields]
2[0]=name&populate[heroImage][fields]
3[1]=alternativeText&populate[heroImage][fields]
4[2]=caption&populate[heroImage][fields]
5[3]=url&populate[authors][fields]
6[0]=username&populate[authors][populate][role][fields]
7[0]=name
While this correctly returns the data specified, it is not feasible to use. This query is quite unruly and certainly not something you'd want to consistently use throughout your application.
Using query-string, we can implement the same query as above in a much more readable and reusable manner. The query can easily be used directly in the front-end of our application.
For example:
1const qs = require('qs')
2const query = qs.stringify(
3 {
4 populate: {
5 heroImage: {
6 fields: ['name', 'alternativeText', 'caption', 'url'],
7 },
8 authors: {
9 fields: ['username'],
10 populate: {
11 role: {
12 fields: ['name'],
13 },
14 },
15 },
16 },
17 },
18 {
19 encodeValuesOnly: true, // prettify URL
20 }
21)
22// `localhost:1337/api/blog-posts?${query}`
It successfully returns the same result as the above query where we used bracket syntax:
1{
2 "data": [
3 {
4 "id": 1,
5 "attributes": {
6 "title": "Test Blog Post",
7 "body": "Test blog content",
8 "slug": "test-blog-post",
9 "createdAt": "2022-08-09T18:45:19.012Z",
10 "updatedAt": "2022-08-09T19:22:39.637Z",
11 "publishedAt": "2022-08-09T18:45:21.707Z",
12 "heroImage": {
13 "data": {
14 "id": 1,
15 "attributes": {
16 "name": "test_cat.jpeg",
17 "alternativeText": "test_cat.jpeg",
18 "caption": "test_cat.jpeg",
19 "url": "/uploads/test_cat_2bdaa9fbe9.jpeg"
20 }
21 }
22 },
23 "authors": {
24 "data": {
25 "id": 1,
26 "attributes": {
27 "username": "testUser"
28 }
29 }
30 }
31 }
32 }
33 ],
34 "meta": {
35 "pagination": {
36 "page": 1,
37 "pageSize": 25,
38 "pageCount": 1,
39 "total": 1
40 }
41 }
42}
For many use cases, this will be the logical end. However, if you find that you are re-using the same query over and over again, read on.
Now that you know how to build useful queries, you can look at optimizing the process further by adding a query directly into route-based middleware.
In Strapi, you can generate boilerplate code directly from the CLI. In your terminal, run the command:
yarn strapi generate
From there, navigate to middleware
.
You will be prompted to name the middleware. Then, you will need to select where you want to add this middleware.
For this example, choose Add middleware to an existing API
since you only want it to run on the blog-post route.
Now in the Strapi project, if you navigate to src > api > blog-post > middlewares > test.js
, you will see the following boilerplate:
1'use strict'
2
3/**
4* `test` middleware.
5*/
6
7module.exports = (config, { strapi }) => {
8 // Add your own logic here.
9 return async (ctx, next) => {
10 strapi.log.info('In test middleware.')
11
12 await next()
13 }
14}
Before utilizing the middleware, you first need to enable it on the route.
If you head to src > api > blog-post > routes > blog-post.js
, you'll see the default route configuration:
1'use strict'
2
3/**
4* blog-post router.
5*/
6
7const { createCoreRouter } = require('@strapi/strapi').factories
8
9module.exports = createCoreRouter('api::blog-post.blog-post')
Edit this file as follows:
1'use strict'
2
3/**
4* blog-post router.
5*/
6
7const { createCoreRouter } = require('@strapi/strapi').factories
8
9module.exports = createCoreRouter('api::blog-post.blog-post', {
10 config: {
11 find: {
12 middlewares: ['api::blog-post.test'],
13 },
14 },
15})
Pro Tip: If you can't remember the internal UIDs of the middleware, which is
api::blog-post.test
, run the command below:
yarn strapi middlewares:list
This will give you a list of all internal middleware UIDs in your project
To see all of the available customizations for core routes, check out the docs.
Now that thw middleware has been initialized in your project and added to the blog-post
route, it's time to add some logic.
The purpose of this middleware is so you do not need to build your query on the frontend to return the data you are looking to fetch.
By adding your logic directly to the middleware, all of the querying will happen automatically when you head to the localhost:1337/api/blog-post
route.
Instead of writing your query on the frontend, add it directly to the middleware, as such:
1// src > api > blog-post > middlewares > test.js
2
3module.exports = (config, { strapi }) => {
4 // This is where we add our middleware logic
5 return async (ctx, next) => {
6 ctx.query.populate = {
7 heroImage: {
8 fields: ['name', 'alternativeText', 'caption', 'url'],
9 },
10 authors: {
11 fields: ['username'],
12 populate: {
13 role: {
14 fields: ['name'],
15 },
16 },
17 },
18 }
19
20 await next()
21 }
22}
Now, stop the Strapi server and run yarn strapi build
to rebuild your Strapi instance. Once the build is complete, run yarn develop
to restart the Strapi server.
If you go to the route localhost:1337/api/blog-posts
the response returns:
1{
2 "data": [
3 {
4 "id": 1,
5 "attributes": {
6 "title": "Test Blog Post",
7 "body": "Test blog content",
8 "slug": "test-blog-post",
9 "createdAt": "2022-08-09T18:45:19.012Z",
10 "updatedAt": "2022-08-09T19:22:39.637Z",
11 "publishedAt": "2022-08-09T18:45:21.707Z",
12 "heroImage": {
13 "data": {
14 "id": 1,
15 "attributes": {
16 "name": "test_cat.jpeg",
17 "alternativeText": "test_cat.jpeg",
18 "caption": "test_cat.jpeg",
19 "url": "/uploads/test_cat_2bdaa9fbe9.jpeg"
20 }
21 }
22 },
23 "authors": {
24 "data": {
25 "id": 1,
26 "attributes": {
27 "username": "testUser"
28 }
29 }
30 }
31 }
32 }
33 ],
34 "meta": {
35 "pagination": {
36 "page": 1,
37 "pageSize": 25,
38 "pageCount": 1,
39 "total": 1
40 }
41 }
42}
No query string is needed!
Here is a recap of what you've just learned:
populate=*
.Solutions Engineer @ Strapi