# Controllers
Controllers are JavaScript files that contain a set of methods, called actions, reached by the client according to the requested route. Whenever a client requests the route, the action performs the business logic code and sends back the response. Controllers represent the C in the model-view-controller (MVC) pattern. Just like all the other parts of the Strapi backend, controllers can be customized.
In most cases, the controllers will contain the bulk of a project's business logic. But as a controller's logic becomes more and more complicated, it's a good practice to use services to organize the code into re-usable parts.
# Implementation
Controllers can be generated or added manually, and the core controllers examples can help you get started creating custom ones.
# Adding a new controller
A new controller can be implemented:
- with the interactive CLI command
strapi generate
- or manually by creating a JavaScript file in the appropriate folder (see project structure):
./src/api/[api-name]/controllers/
for API controllers- or
./src/plugins/[plugin-name]/controllers/
for plugin controllers.
// path: ./src/api/[api-name]/controllers/my-controller.js
module.exports = {
exampleAction: async (ctx, next) => {
try {
ctx.body = 'ok';
} catch (err) {
ctx.body = err;
}
}
};
Each controller action can be an async
or sync
function.
Every action receives a context object (ctx
) as the first parameter. ctx
contains the request context and the response context.
Example: GET /hello route calling a basic controller
A specific GET /hello
route is defined, which takes hello.index
as a handler. Every time a GET /hello
request is sent to the server, Strapi calls the index
action in the hello.js
controller, which returns Hello World!
:
// path: ./src/api/hello/routes/router.js
module.exports = {
routes: [
{
method: 'GET',
path: '/hello',
handler: 'hello.index',
}
]
}
// path: ./src/api/hello/controllers/hello.js
module.exports = {
index: async (ctx, next) => { // called by GET /hello
ctx.body = 'Hello World!'; // we could also send a JSON
},
};
✏️ NOTE
When a new content-type is created, Strapi builds a generic controller with placeholder code, ready to be customized.
# Extending core controllers
Strapi's core API provide actions built into controller files for collection types and single types. The following code examples should help you get started creating custom actions for controllers:
Collection type examples
Single type examples
# Usage
Controllers are called different ways depending on their scope:
- for API controllers, use:
strapi.api('api-name').controller('controller-name')
- or
strapi.controller('api::api-name.controller-name')
- for plugin controllers, use:
strapi.plugin('plugin-name').controller('controller-name')
- or
strapi.controller('plugin::plugin-name.controller-name')