Skip to main content

Requests & Responses

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 and files through ctx.request.files

For more information, please refer to the Koa request 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.