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

When you send requests through the REST API, 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.

CTX Table

ctx

ParameterDescriptionType
ctxCtx is the context object that is given to every layer within strapiObject

ctx.request

ParameterDescriptionType
ctx.requestThe request you got from the client that did an api request.Object
ctx.request.bodyParsed version of the bodyObject
ctx.request.paramsThe params send in the url. Example /${info.pluralName}/:id then the :id part would create a param named id. To get the example parm you would do ctx.request.params.id.Object
ctx.request.filesthe files send with the request.Array
ctx.request.headersAll headers send with the request.Object
ctx.request.urlGives you back the url from the first /.String
ctx.request.originGives you back the url without the / and everything behind it.String
ctx.request.hrefGives you back the full url excluding the params.String
ctx.request.methodGives you back the method examples of methods are GET or POST.String
ctx.request.pathGives you back the full url.String
ctx.request.hostOnly gives the host part of the url.String
ctx.request.hostOnly gives the host part of the url without the portString
ctx.request.hostProtocol being used examples: https or http.String
ctx.request.ipsWhen X-Forwarded-For is present and app.proxy is enabled an array of these ips is returned, ordered from upstream -> downstream. For example if the value were "client, proxy1, proxy2", you would receive the array ["client", "proxy1", "proxy2"].Array
ctx.request.ipIP of the person who send the request.String
ctx.request.subdomainsFor example, if the domain is "tobi.ferrets.example.com": it is ["ferrets", "tobi"].Array

ctx.request.query

ParameterDescriptionType
ctx.request.query
ctx.query
API parameters can be used with the REST API to filter, sort, and paginate results and to select fields and relations to populateObject
ctx.request.query.sort Sort the responseString
Array
ctx.request.query.filtersFilter the responseObject
ctx.request.query.populate Populate relations, components, or dynamic zonesString
Object
ctx.request.query.fields Select only specific fields to displayArray
ctx.request.query.pagination Page through entriesObject
ctx.request.query.publicationState Select the Draft & Publish state

Only accepts the following values:
  • live(default)
  • preview
String
ctx.request.query.locale Select one or multiple localesString
Array

ctx.response

ParameterDescriptionType
ctx.response The response the server will give backObject
ctx.response.body The body of the responseAny
ctx.response.statusthe status code of the responseInteger
ctx.response.message Get response status message. By default, response.message is associated with response.status.String
ctx.response.header
ctx.response.headers
The headers of the responseObject
ctx.response.length Return response Content-Length as a number when present, or deduce from ctx.body when possible, or undefined.Integer
ctx.response.redirect ctx.response.redirect(url, [alt]) Perform a [302] redirect to url. The string "back" is special-cased to provide Referrer support, when Referrer is not present alt or "/" is used. Example: ctx.response.redirect('back', '/index.html');Function
ctx.response.attachment ctx.response.attachment([filename], [options])
Set Content-Disposition to "attachment" to signal the client to prompt for download. Optionally specify the filename of the download and some options.Function
ctx.response.typeGet response Content-Type void of parameters such as "charset".String
ctx.response.lastModifiedReturn the Last-Modified header as a Date, if it exists.DateTime
ctx.response.etagSet the ETag of a response including the wrapped "s. Note that there is no corresponding response.etag getter.String

ctx.state

ParameterDescriptionType
ctx.state the strapi state of the requestObject
ctx.state.isAuthenticatedTells you if the current user is authenticated in any wayBoolean

ctx.state.user

ParameterDescriptionType
ctx.state.userNormal user object where all fields are there but only role relation is populatedObject
ctx.state.user.roleThe users roleObject

ctx.state.auth

ParameterDescriptionType
ctx.state.auththe auth objectObject
ctx.state.auth.strategythe object of the currently used strategyObject
ctx.state.auth.strategy.namethe name of the currently used strategyString

ctx.state.route

ParameterDescriptionType
ctx.state.routethe object with all the information of the current routeObject
ctx.state.route.methodmethod of the current routeString
ctx.state.route.pathpath of the current routeString
ctx.state.route.configAll configuration of the routeObject

ctx.state.info

ParameterDescriptionType
ctx.state.infoThe info objectObject
ctx.state.info.apiNameThe name of the used apiString
ctx.state.info.typethe type of the used apiString

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.