Skip to content

Commit d3416db

Browse files
authored
Fully describe the Koa context object passed to Strapi (#1786)
* Rework the request part * Rework intro * Rework intro * Improve ctx.request, ctx.state, and ctx.response * Move section higher up in the TOC
1 parent 4177023 commit d3416db

File tree

2 files changed

+129
-10
lines changed

2 files changed

+129
-10
lines changed

docusaurus/docs/dev-docs/backend-customization/requests-responses.md

Lines changed: 128 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,140 @@ description: Learn more about requests and responses for Strapi, the most popula
44

55
---
66

7-
# Requests & Responses
7+
# Requests and Responses
88

9-
## Requests
9+
The Strapi back end server is based on [Koa](https://koajs.com/). When you send requests through the [REST API](/dev-docs/api/rest), a context object (`ctx`) is passed to every element of the Strapi back end (e.g., [policies](/dev-docs/backend-customization/policies), [controllers](/dev-docs/backend-customization/controllers), [services](/dev-docs/backend-customization/services)).
1010

11-
When you send requests through the [REST API](/dev-docs/api/rest), the context object (`ctx`) contains all the requests related information. They are accessible through `ctx.request`, from [controllers](/dev-docs/backend-customization/controllers.md) and [policies](/dev-docs/backend-customization/policies.md).
11+
`ctx` includes 3 main objects:
1212

13-
Strapi passes the `body` on `ctx.request.body`, `query` on `ctx.request.query`, `params` on `ctx.request.params` and `files` through `ctx.request.files`
13+
- [`ctx.request`](#ctxrequest) for information about the request sent by the client making an API request,
14+
- [`ctx.state`](#ctxstate) for information about the state of the request within the Strapi back end,
15+
- and [`ctx.response`](#ctxresponse) for information about the response that the server will return.
1416

15-
For more information, please refer to the [Koa request documentation](http://koajs.com/#request) and [Koa Router documentation](https://github.com/koajs/router/blob/master/API.md).
16-
17-
## Responses
17+
:::tip
18+
The request's context can also be accessed from anywhere in the code with the [`strapi.requestContext` function](#accessing-the-request-context-anywhere).
19+
:::
1820

19-
The context object (`ctx`) contains a list of values and functions useful to manage server responses. They are accessible through `ctx.response`, from [controllers](/dev-docs/backend-customization/controllers.md) and [policies](/dev-docs/backend-customization/policies.md).
21+
:::info
22+
In addition to the concepts and parameters described in the following documentation, you might find additional information in the [Koa request documentation](http://koajs.com/#request), [Koa Router documentation](https://github.com/koajs/router/blob/master/API.md) and [Koa response documentation](http://koajs.com/#response).
23+
:::
2024

21-
For more information, please refer to the [Koa response documentation](http://koajs.com/#response).
25+
## `ctx.request`
26+
27+
The `ctx.request` object contains the following parameters:
28+
29+
| Parameter | Description | Type |
30+
| --------------------- | -------------------------------------------------------------------------------------------- | -------- |
31+
| `ctx.request.body` | Parsed version of the body. | `Object` |
32+
| `ctx.request.files` | Files sent with the request. | `Array` |
33+
| `ctx.request.headers` | Headers sent with the request. | `Object` |
34+
| `ctx.request.host` | Host part of the URL, including the port. | `String` |
35+
| `ctx.request.hostname`| Host part of the URL, excluding the port. | `String` |
36+
| `ctx.request.href` | Complete URL of the requested resource, including the protocol, domain, port (if specified), path, and query parameters. | `String` |
37+
| `ctx.request.ip` | IP of the person sending the request.| `String` |
38+
| `ctx.request.ips` | When `X-Forwarded-For` is present and `app.proxy` is enabled, an array of IPs is returned, ordered from upstream to downstream. <br /><br />For example if the value were "client, proxy1, proxy2", you would receive the `["client", "proxy1", "proxy2"]` array. | `Array` |
39+
| `ctx.request.method` | Request method (e.g., `GET`, `POST`). | `String` |
40+
| `ctx.request.origin` | URL part before the first `/`. | `String` |
41+
| `ctx.request.params` | Query parameters sent in the URL.<br /><br/>For example, if the request URL includes includes something like `/restaurants?id`, the `?id` part creates an `id` parameter accessible through `ctx.request.params.id`. | `Object` |
42+
| `ctx.request.path` | Path of the requested resource, excluding the query parameters. | `String` |
43+
| `ctx.request.protocol`| Protocol being used (e.g., `https` or `http`). | `String` |
44+
| `ctx.request.query` | Strapi-specific [query parameters](#ctxrequestquery). | `Object` |
45+
| `ctx.request.subdomains`| Subdomains included in the URL.<br /><br />For example, if the domain is `tobi.ferrets.example.com`, the value is the following array: `["ferrets", "tobi"]`. | `Array` |
46+
| `ctx.request.url` | Path and query parameters of the requested resource, excluding the protocol, domain, and port. | `String` |
47+
48+
<details>
49+
<summary>Differences between protocol, origin, url, href, path, host, and hostname :</summary>
50+
51+
Given an API request sent to the `https://example.com:1337/api/restaurants?id=123` URL, here is what different parameters of the `ctx.request` object return:
52+
53+
| Parameter | Returned value |
54+
| ---------- | ------------------------------------------------- |
55+
| `ctx.request.href` | `https://example.com:1337/api/restaurants?id=123` |
56+
| `ctx.request.protocol` | `https` |
57+
| `ctx.request.host` | `localhost:1337` |
58+
| `ctx.request.hostname` | `localhost` |
59+
| `ctx.request.origin` | `https://example.com:1337` |
60+
| `ctx.request.url` | `/api/restaurants?id=123` |
61+
| `ctx.request.path` | `/api/restaurants` |
62+
63+
</details>
64+
65+
### `ctx.request.query`
66+
67+
`ctx.request` provides a `query` object that gives access to Strapi query parameters. The following table lists available parameters with a short description and a link to the relevant REST API documentation section (see [REST API parameters](/dev-docs/api/rest/parameters) for more information):
68+
69+
| Parameter | Description | Type |
70+
| -------------------------------------| --------------------------------------------------------------------------------------------------------------------------- | -------------------- |
71+
| `ctx.request.query`<br />`ctx.query` | The whole query object. | `Object` |
72+
| `ctx.request.query.sort` | Parameters to [sort the response](/dev-docs/api/rest/sort-pagination.md#sorting) | `String` or `Array` |
73+
| `ctx.request.query.filters` | Parameters to [filter the response](/dev-docs/api/rest/filters-locale-publication#filtering) | `Object` |
74+
| `ctx.request.query.populate` | Parameters to [populate relations, components, or dynamic zones](/dev-docs/api/rest/populate-select#population) | `String` or `Object` |
75+
| `ctx.request.query.fields` | Parameters to [select only specific fields to return with the response](/dev-docs/api/rest/populate-select#field-selection) | `Array` |
76+
| `ctx.request.query.pagination` | Parameter to [page through entries](/dev-docs/api/rest/sort-pagination.md#pagination) | `Object` |
77+
| `ctx.request.query.publicationState` | Parameter to [select the Draft & Publish state](/dev-docs/api/rest/filters-locale-publication#publication-state) | `String` |
78+
| `ctx.request.query.locale` | Parameter to [select one or multiple locales](/dev-docs/api/rest/filters-locale-publication#locale) | `String` or `Array` |
79+
80+
## `ctx.state`
81+
82+
The `ctx.state` object gives access to the state of the request within the Strapi back end, including specific values about the [user](#ctxstateuser), [authentication](#ctxstateauth), [route](#ctxstateroute):
83+
84+
| Parameter | Description | Type |
85+
| ---------------------------|---------------------------------------------------------------------------- | -------- |
86+
| `ctx.state.isAuthenticated`| Returns whether the current user is authenticated in any way. | `Boolean` |
87+
88+
### `ctx.state.user`
89+
90+
The `ctx.state.user` object gives access to information about the user performing the request and includes the following parameters:
91+
92+
| Parameter | Description | Type |
93+
| ----------| -------------------------------------------------------------------------------------------- | -------- |
94+
| `ctx.state.user`| User's information. Only one relation is populated. | `Object` |
95+
| `ctx.state.user.role`| The user's role | `Object` |
96+
<!-- which type of "user" are we talking about here? a "U&P"-related user? -->
97+
98+
### `ctx.state.auth`
99+
100+
The `ctx.state.auth` object gives access to information related to the authentication and includes the following parameters:
101+
102+
| Parameter | Description | Type |
103+
| ------------------------------| -------------------------------------------------------------------------------------------- | -------- |
104+
| `ctx.state.auth.strategy` | Information about the currently used authentication strategy ([Users & Permissions plugin](/dev-docs/plugins/users-permissions) or [API tokens](/dev-docs/configurations/api-tokens)) | `Object` |
105+
| `ctx.state.auth.strategy.name`| Name of the currently used strategy | `String` |
106+
| `ctx.state.auth.credentials` | The user's credentials | `String` |
107+
<!-- ? ctx.state.auth.strategy seems to include the authenticate and verify functions. should we document them somewhere? -->
108+
<!-- ? not sure what credentials are used for ? -->
109+
110+
### `ctx.state.route`
111+
112+
The `ctx.state.route` object gives access to information related to the current route and includes the following parameters:
113+
114+
| Parameter | Description | Type |
115+
| ----------| -------------------------------------------------------------------------------------------- | -------- |
116+
| `ctx.state.route.method`| Method used to access the current route. | `String` |
117+
| `ctx.state.route.path`| Path of the current route. | `String` |
118+
| `ctx.state.route.config`| Configuration information about the current route. | `Object` |
119+
| `ctx.state.route.handler`| Handler (controller) of the current route. | `Object` |
120+
| `ctx.state.route.info`| Additional information about the current route, such as the apiName and the API request type. | `Object` |
121+
| `ctx.state.route.info.apiName`| Name of the used API. | `String` |
122+
| `ctx.state.route.info.type`| Type of the used API. | `String` |
123+
124+
## `ctx.response`
125+
126+
The `ctx.response` object gives access to information related to the response that the server will return and includes the following parameters:
127+
128+
| Parameter | Description | Type |
129+
| ----------| -------------------------------------------------------------------------------------------- | -------- |
130+
| `ctx.response.body`| Body of the response. | `Any` |
131+
| `ctx.response.status` | Status code of the response. | `Integer` |
132+
| `ctx.response.message`| Status message of the response.<br/><br />By default, `response.message` is associated with `response.status`. | `String` |
133+
| `ctx.response.header`<br />`ctx.response.headers`| Header(s) sent with the response. | `Object` |
134+
| `ctx.response.length`| [`Content-Length`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length) header value as a number when present, or deduces it from `ctx.body` when possible; otherwise, returns `undefined`. | `Integer` |
135+
| `ctx.response.redirect`<br />`ctx.response.redirect(url, [alt])` | Performs a `302` redirect to the URL. The string "back" is special-cased to provide Referrer support; when Referrer is not present, alt or "/" is used.<br /><br />Example: `ctx.response.redirect('back', '/index.html');` | `Function` |
136+
| `ctx.response.attachment`<br /><br />`ctx.response.attachment([filename], [options])` | Sets [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) header to "attachment" to signal the client to prompt for download. Optionally specify the filename of the download and some [options](https://github.com/jshttp/content-disposition#options). | `Function` |
137+
| `ctx.response.type`| [`Content-Type`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) header, void of parameters such as "charset". | `String` |
138+
| `ctx.response.lastModified`| [`Last-Modified`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified) header as a Date, if it exists. | `DateTime` |
139+
| `ctx.response.etag`| Sets the [`ETag`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) of a response including the wrapped "s.<br/>There is no corresponding `response.etag` getter. | `String` |
140+
<!-- I don't understand what these 5 last lines above mean, just copied and pasted them from the user's PR 🤷 — piwi -->
22141

23142
## Accessing the request context anywhere
24143

docusaurus/sidebars.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,11 +215,11 @@ const sidebars = {
215215
id: 'dev-docs/backend-customization',
216216
},
217217
items: [
218+
'dev-docs/backend-customization/requests-responses',
218219
'dev-docs/backend-customization/routes',
219220
'dev-docs/backend-customization/policies',
220221
'dev-docs/backend-customization/middlewares',
221222
'dev-docs/backend-customization/controllers',
222-
'dev-docs/backend-customization/requests-responses',
223223
'dev-docs/backend-customization/services',
224224
'dev-docs/backend-customization/models',
225225
'dev-docs/backend-customization/webhooks',

0 commit comments

Comments
 (0)