# 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 (opens new window).
# 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 (opens new window).
# 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);
},
};
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Example:
//path: ./api/test/content-types/article/lifecycles.js
module.exports = {
beforeUpdate() {
const ctx = strapi.requestContext.get();
console.log('User info in service: ', ctx.state.user);
},
};
2
3
4
5
6
7
8
9
✏️ NOTE
Strapi uses a Node.js feature called AsyncLocalStorage (opens new window) to make the context available anywhere.
← Controllers Services →