Skip to main content

Requests & Responses

💬 Strapi team needs you to improve this documentation!

We are currently reworking the Backend Customization section of the Strapi documentation. If you would like to help, please feel free to fill in this form to share with us your opinions, needs and requests.

Requests

The context object (ctx) contains all the requests related information. They are accessible through ctx.request, from controllers and policies.

Strapi passes the body on ctx.request.body, query on ctx.request.query, params on ctx.request.params and files through ctx.request.files

For more information, please refer to the Koa request documentation and Koa Router documentation.

Responses

The context object (ctx) contains a list of values and functions useful to manage server responses. They are accessible through ctx.response, from controllers and policies.

For more information, please refer to the Koa response documentation.

Accessing the request context anywhere

✨ New in v4.3.9

The strapi.requestContext works with Strapi v4.3.9+.

Strapi exposes a way to access the current request context from anywhere in the code (e.g. lifecycle functions).

You can access the request as follows:

const ctx = strapi.requestContext.get();

You should only use this inside of functions that will be called in the context of an HTTP request.

// correct

const service = {
myFunction() {
const ctx = strapi.requestContext.get();
console.log(ctx.state.user);
},
};

// incorrect
const ctx = strapi.requestContext.get();

const service = {
myFunction() {
console.log(ctx.state.user);
},
};

Example:

./api/test/content-types/article/lifecycles.js

module.exports = {
beforeUpdate() {
const ctx = strapi.requestContext.get();

console.log('User info in service: ', ctx.state.user);
},
};
✏️ Note

Strapi uses a Node.js feature called AsyncLocalStorage to make the context available anywhere.