Strapi V4 customizable plugin configs
I have been struggling to find the correct way or syntax to allow users to customize a plugin configuration via config/plugins.ts
. This article is a quick sharing of how I accomplished this.
There are two areas where you may want to use the plugin configs:
Plugin frontend (Admin panel)
Plugin backend (Server-side code)
Using configs on the backend
Since the backend side is more straightforward, let's start with it first.
Here you put your default plugin configs. /{your-plugin-name}/server/config/index.ts
export default {
default: ({ env }) => ({
// Your default value here
}),
validator: (config) => {
// Your validation logic here
},
};
To use the configs in your controllers or services, you can access them through the strapi
context available for server-side code.
/{your-plugin-name}/controllers/myController.ts
import { Strapi } from "@strapi/strapi";
import pluginId from "../../admin/src/pluginId";
export default ({ strapi }: { strapi: Strapi }) => ({
get(ctx) {
const configs = strapi.config.get(`plugin.${pluginId}`);
return configs;
},
});
** Please note that if you provide an array in your default config and the user also provides an array value, the result will be a merge instead of a replacement.
For example:
/{your-plugin-name}/server/config/index.ts
export default {
default: ({ env }) => ({
names: ['Sam','Peter']
}),
};
/{user-strapi-project}/config/plugins.ts
export default {
"your-plugin-name": {
"enabled": true,
"config": {
"names": ["Mary","Sam"]
}
}
};
In this case, the names
config would be ["Sam", "Peter", "Mary"]
.
Using configs on the frontend
In Strapi V4, the Strapi context is no longer globally available, which means you can no longer access the configs directly.
Instead, you can create an API to expose the config to the frontend.
- Create a route on your plugin backend at
{your-plugin-name}/server/routes/index.ts
:
export default [
{
method: "GET",
path: "/",
handler: "configs.get",
config: {
policies: []
},
},
];
- Create a controller at
{your-plugin-name}/server/controllers/index.ts
:
import { Strapi } from "@strapi/strapi";
import pluginId from "../../admin/src/pluginId";
const configsController = ({ strapi }: { strapi: Strapi }) => ({
get(ctx) {
const configs = strapi.config.get(`plugin.${pluginId}`);
return configs;
},
});
export default {
config: configsController
}
- Consume the API in your admin panel React component using the Node.js built-in
fetch
or a library likeaxios
:
fetch(`/${pluginId}`)
.then((response) => response.json())
.then((data) => {
setConfigs(data);
});
That's all! Thank you so much for taking the time to read!
Subscribe to my newsletter
Read articles from Kwinten directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by