# Account billing details
Source: https://docs.strapi.io/cloud/account/account-billing
# Account billing & invoices
Through the *Profile* page, accessible by clicking on your profile picture on the top right hand corner of the interface then clicking on **Profile**, you can access the [ *Billing*](#account-billing) and [ *Invoices*](#account-invoices) tabs.
## Account billing
The *Billing* tab displays and enables you to modify the billing details and payment method set for the account.
The *Payment method* section of the *Billing* tab allows you to manage the credit cards that can be used for the Strapi Cloud projects. The *Billing details* section requires to be filled in, at least for the mandatory fields, as this information will be the default billing details for all Strapi Cloud projects related to your account.
### Adding a new credit card
1. In the *Payment method* section of the *Billing* tab, click on the **Add card** button.
2. Fill in the following fields:
| Field name | Description |
| --- | --- |
| Card Number | Write the number of the credit card to add as payment method. |
| Expires | Write the expiration date of the credit card. |
| CVC | Write the 3-numbers code displayed at the back of the credit card. |
3. Click on the **Save** button.
:::tip
The first credit card to be added as payment method for the account will by default be the primary one. It is however possible to define another credit card as primary by clicking on the icon, then **Switch as primary**.
:::
### Deleting a credit card
To remove a credit card from the list of payment methods for the account:
1. Click on the icon of the credit card you wish to delete.
2. Click **Remove card**. The card is immediately deleted.
:::note
You cannot delete the primary card as at least one credit card must be available as payment method, and the primary card is by default that one. If the credit card you wish to delete is currently the primary card, you must first define another credit card as primary, then delete it.
:::
## Account invoices
The *Invoices* tab displays the complete list of invoices for all your Strapi Cloud projects.
:::strapi Invoices are also available per project.
In the *Settings > Invoices* tab of any project, you will find the invoices for that project only. Feel free to check the [dedicated documentation](/cloud/projects/settings#invoices).
:::
# Profile settings
Source: https://docs.strapi.io/cloud/account/account-settings
# Profile settings
The *Profile* page enables you to manage your account details and preferences. It is accessible by clicking on your profile picture, on the top right hand corner of the interface, and **Profile**.
There are 3 tabs available in the *Profile* interface: [*General*](#general), *Billing* and Invoices (the last 2 are documented in the [Account billing details](/cloud/account/account-billing) section of this documentation).
## General
The *General* tab enables you to edit the following details for your account profile:
- Details: to see the name associated with your account.
- Connected accounts: to manage Google, GitHub, GitLab and email accounts connected with your Strapi Cloud account (see [Managing connected accounts](#managing-connected-accounts)).
- Delete account: to permanently delete your Strapi Cloud account (see [Deleting Strapi Cloud account](#deleting-strapi-cloud-account)).
### Managing connected accounts
You can connect a Google, GitLab, GitHub and email account to your Strapi Cloud account. The _Connected accounts_ section lists accounts that are currently connected to your Strapi Cloud account. From there you can also connect a new Google, GitLab, GitHub and email account if one is not already connected.
To connect a new Google, GitLab, GitHub or email account to your Strapi Cloud account, click on the **Connect account** button and follow the next steps on the corresponding website.
You can also click on the three dots button of a connected account and click on the "Manage on" button to manage your GitHub, GitLab or Google account directly on the corresponding website.
### Deleting Strapi Cloud account
You can delete your Strapi Cloud account, but it will be permanent and irreversible. All associated projects and their data will be deleted as well and the subscriptions for the projects will automatically be canceled.
1. In the *Delete account* section of the *General* tab, click on the **Delete account** button.
2. In the dialog, type `DELETE` in the textbox.
3. Confirm the deletion of your account by clicking on the **Delete** button.
# Database
Source: https://docs.strapi.io/cloud/advanced/database
# Database
Strapi Cloud provides a pre-configured PostgreSQL database by default. However, you can also configure it to utilize an external SQL database, if needed.
:::prerequisites
- A local Strapi project running on `v4.8.2+`.
- Credentials for an external database.
- If using an existing database, the schema must match the Strapi project schema.
:::
:::caution
While it's possible to use an external database with Strapi Cloud, you should do it while keeping in mind the following considerations:
- Strapi Cloud already provides a managed database that is optimized for Strapi.
- Using an external database may result in unexpected behavior and/or performance issues (e.g., network latency may impact performance). For performance reasons, it's recommended to host your external database close to the region where your Strapi Cloud project is hosted. You can find where your Strapi Cloud project is hosted in your Project Settings (see [Project Settings > General > Selected Region](/cloud/projects/settings#general)).
- Strapi can't provide security or support with external databases used with Strapi Cloud.
:::
:::warning
Any environment variable added to your project that starts with `DATABASE_` will cause Strapi Cloud to assume that you will be using an external database and all Strapi Cloud specific database variables will not be injected!
:::
## Configuration
The project `./config/database.js` or `./config/database.ts` file must match the configuration found in the [environment variables in database configurations](https://docs.strapi.io/cms/configurations/database#environment-variables-in-database-configurations) section.
Before pushing changes, add environment variables to the Strapi Cloud project:
1. Log into Strapi Cloud and click on the corresponding project on the Projects page.
2. Click on the **Settings** tab and choose **Variables** in the left menu.
3. Add the following environment variables:
| Variable | Value | Details |
| ---------------------------------- | ---------------- |----------|
| `DATABASE_CLIENT` | your_db | Should be one of `mysql`, `postgres`, or `sqlite`. |
| `DATABASE_HOST` | your_db_host | The URL or IP address of your database host |
| `DATABASE_PORT` | your_db_port | The port to access your database |
| `DATABASE_NAME` | your_db_name | The name of your database |
| `DATABASE_USERNAME` | your_db_username | The username to access your database |
| `DATABASE_PASSWORD` | your_db_password | The password associated to this username |
| `DATABASE_SSL_REJECT_UNAUTHORIZED` | false | Whether unauthorized connections should be rejected |
| `DATABASE_SCHEMA` | public | - |
4. Click **Save**.
:::caution
To ensure a smooth deployment, it is recommended to not change the names of the environment variables.
:::
## Deployment
To deploy the project and utilize the external database, push the changes from earlier. This will trigger a rebuild and new deployment of the Strapi Cloud project.
Once the application finishes building, the project will use the external database.
## Reverting to the default database
To revert back to the default database, remove the previously added environment variables related to the external database from the Strapi Cloud project dashboard, and save. For the changes to take effect, you must redeploy the Strapi Cloud project.
# Email Provider
Source: https://docs.strapi.io/cloud/advanced/email
# Email Providers configuration for Strapi Cloud
Strapi Cloud comes with a basic email provider out of the box. However, it can also be configured to utilize another email provider, if needed.
:::caution
Please be advised that Strapi is unable to provide support for third-party email providers.
:::
:::prerequisites
- A local Strapi project running on `v4.8.2+`.
- Credentials for another email provider (see
:::caution
The file structure must match the above path exactly, or the configuration will not be applied to Strapi Cloud.
:::
Each provider will have different configuration settings available. Review the respective entry for that provider in the
:::tip
Before pushing the above changes to GitHub, add environment variables to the Strapi Cloud project to prevent triggering a rebuild and new deployment of the project before the changes are complete.
:::
### Strapi Cloud Configuration
1. Log into Strapi Cloud and click on the corresponding project on the Projects page.
2. Click on the **Settings** tab and choose **Variables** in the left menu.
3. Add the required environment variables specific to the email provider.
4. Click **Save**.
**Example:**
## Deployment
To deploy the project and utilize another party email provider, push the changes from earlier. This will trigger a rebuild and new deployment of the Strapi Cloud project.
Once the application finishes building, the project will use the new email provider.
:::strapi Custom Provider
If you want to create a custom email provider, please refer to the [Email providers](/cms/features/email#providers) documentation in the CMS Documentation.
:::
# Upload Provider Configuration for Strapi Cloud
Source: https://docs.strapi.io/cloud/advanced/upload
# Upload Provider Configuration for Strapi Cloud
Strapi Cloud comes with a local upload provider out of the box. However, it can also be configured to utilize a third-party upload provider, if needed.
:::caution
Please be advised that Strapi is unable to provide support for third-party upload providers.
:::
:::prerequisites
- A local Strapi project running on `v4.8.2+`.
- Credentials for a third-party upload provider (see
:::caution
The file structure must match the above path exactly, or the configuration will not be applied to Strapi Cloud.
:::
Each provider will have different configuration settings available. Review the respective entry for that provider in the
### Configure the Security Middleware
Due to the default settings in the Strapi Security Middleware you will need to modify the `contentSecurityPolicy` settings to properly see thumbnail previews in the Media Library.
To do this in your Strapi project:
1. Navigate to `./config/middlewares.js` or `./config/middlewares.ts` in your Strapi project.
2. Replace the default `strapi::security` string with the object provided by the upload provider.
**Example:**
:::tip
Before pushing the above changes to GitHub, add environment variables to the Strapi Cloud project to prevent triggering a rebuild and new deployment of the project before the changes are complete.
:::
### Strapi Cloud Configuration
1. Log into Strapi Cloud and click on the corresponding project on the Projects page.
2. Click on the **Settings** tab and choose **Variables** in the left menu.
3. Add the required environment variables specific to the upload provider.
4. Click **Save**.
**Example:**
## Deployment
To deploy the project and utilize the third-party upload provider, push the changes from earlier. This will trigger a rebuild and new deployment of the Strapi Cloud project.
Once the application finishes building, the project will use the new upload provider.
:::strapi Custom Provider
If you want to create a custom upload provider, please refer to the [Providers](/cms/features/media-library#providers) documentation in the CMS Documentation.
:::
# Command Line Interface (CLI)
Source: https://docs.strapi.io/cloud/cli/cloud-cli
# Command Line Interface (CLI)
Strapi Cloud comes with a Command Line Interface (CLI) which allows you to log in and out, and to deploy a local project without it having to be hosted on a remote git repository. The CLI works with both the `yarn` and `npm` package managers.
:::note
It is recommended to install Strapi locally only, which requires prefixing all of the following `strapi` commands with the package manager used for the project setup (e.g `npm run strapi help` or `yarn strapi help`) or a dedicated node package executor (e.g. `npx strapi help`).
:::
## strapi login
**Alias:** `strapi cloud:login`
Log in Strapi Cloud.
```bash
strapi login
```
This command automatically opens a browser window to first ask you to confirm that the codes displayed in both the browser window and the terminal are the same. Then you will be able to log into Strapi Cloud via Google, GitHub or GitLab. Once the browser window confirms successful login, it can be safely closed.
If the browser window doesn't automatically open, the terminal will display a clickable link as well as the code to enter manually.
## strapi deploy
**Alias:** `strapi cloud:deploy`
Deploy a new local project (< 100MB) in Strapi Cloud.
```bash
strapi deploy
```
This command must be used after the `login` one. It deploys a local Strapi project on Strapi Cloud, without having to host it on a remote git repository beforehand. The terminal will inform you when the project is successfully deployed on Strapi Cloud.
Deploying a Strapi project through the CLI creates a project on the Free plan.
Once the project is first deployed on Strapi Cloud with the CLI, the `deploy` command can be reused to trigger a new deployment of the same project.
:::note
Once you deployed your project, if you visit the Strapi Cloud dashboard, you may see some limitations as well as impacts due to creating a Strapi Cloud project that is not in a remote repository and which was deployed with the CLI.
- Some areas in the dashboard that are usually reserved to display information about the git provider will be blank.
- Some buttons, such as the **Trigger deploy** button, will be greyed out and unclickable since, unless you have [connected a git repository to your Strapi Cloud project](/cloud/getting-started/deployment-cli#automatically-deploying-subsequent-changes).
:::
## strapi link
**Alias:** `strapi cloud:link`
Links project in the current folder to an existing project in Strapi Cloud.
```bash
strapi link
```
This command connects your local project in the current directory with an existing project on your Strapi Cloud account. You will be prompted to select the project you wish to link from a list of available projects hosted on Strapi Cloud.
## strapi projects
**Alias:** `strapi cloud:projects`
Lists all Strapi Cloud projects associated with your account.
```bash
strapi projects
```
This command retrieves and displays a list of all projects hosted on your Strapi Cloud account.
## strapi logout
**Alias:** `strapi cloud:logout`
Log out of Strapi Cloud.
```bash
strapi logout
```
This command logs you out of Strapi Cloud. Once the `logout` command is run, a browser page will open and the terminal will display a confirmation message that you were successfully logged out. You will not be able to use the `deploy` command anymore.
# Caching & Performance
Source: https://docs.strapi.io/cloud/getting-started/caching
# Caching & Performance
For Strapi Cloud applications with large amounts of cacheable content, such as images, videos, and other static assets, enabling CDN (Content Delivery Network) caching via the
# Strapi Cloud の基礎
Source: https://docs.strapi.io/cloud/getting-started/cloud-fundamentals
# Strapi Cloud の基礎
Strapi Cloud のドキュメントを読み進む前に、ここで紹介する主要な概念を押さえておくことをおすすめします。Strapi Cloud の仕組みの理解とスムーズな利用に役立ちます。
- **ホスティングプラットフォーム** Strapi Cloud は、Strapi CMS(コンテンツ管理システム)で作成した既存の Strapi プロジェクトをデプロイするためのホスティングプラットフォームです。Strapi CMS の SaaS()版ではなく、むしろ PaaS()と捉えてください。Strapi CMS については [CMS ドキュメント](/cms/intro) を参照してください。
- **Strapi Cloud の料金プラン** Strapi Cloud では Free、Essential、Pro、Scale の 4 プランから選べます。プランにより利用できる機能、サポート、カスタマイズの範囲が異なります(詳細は [料金ページ](https://strapi.io/pricing-cloud))。本ドキュメントでは、セクション見出しの下に 、、 バッジが付く場合、その機能は該当する有料プラン以降でのみ利用できます。バッジがない場合は Free プランでも利用できます。
- **Strapi Cloud のユーザーの種類** Strapi Cloud プロジェクトには、オーナーとメンテナーの 2 種類のユーザーがいます。オーナーはプロジェクトを作成したユーザーで、プロジェクトに関するすべての機能・オプションにアクセスできます。メンテナーはオーナーに招待され、既存プロジェクトに参加するユーザーです。メンテナーがダッシュボードで参照・操作できない範囲については [コラボレーション](/cloud/projects/collaboration) を参照してください。
- **サポート** Strapi サポートチームの対応範囲は、契約している Strapi Cloud のプランによります。Free プランにはサポートは含まれません。Essential と Pro は Basic サポート、Scale は Standard サポートです。レベルの詳細は [サポートに関する記事](https://support.strapi.io/support/solutions/articles/67000680833-what-is-supported-by-the-strapi-team#Not-Supported) を参照してください。
- **Strapi Cloud とセルフホストでの API** REST API と GraphQL API の挙動は Strapi Cloud とセルフホストで同じです。違いは主に URL です。
- API のベースドメイン: Strapi Cloud では環境のドメイン(例: `https://.strapiapp.com/api/...`)を使うか、独自ドメインを設定した場合はそのドメインを使います([ドメイン](/cloud/projects/settings#domains))。セルフホストでは公開するドメインを任意に設定します。
- メディアライブラリの URL: Strapi Cloud の REST / GraphQL レスポンスでは、カスタムドメインで API にアクセスしていても、メディアフィールドの URL はプロジェクトのメディアドメイン(例: `.media.strapiapp.com`)になります。セルフホストでは設定したアップロードプロバイダーの URL が返り、自サイトや CDN と一致させられます。セルフホストから Strapi Cloud に移行する場合は、フロントエンドが API が返す絶対 URL を読むか、Strapi Cloud のメディアドメインを受け入れるようにしてください。
# Strapi Cloud - ダッシュボードからのデプロイ
Source: https://docs.strapi.io/cloud/getting-started/deployment
# Cloud ダッシュボードからプロジェクトをデプロイする
初めて Strapi Cloud にプロジェクトを載せるときの、Cloud ダッシュボード利用の手順です。
:::prerequisites
Cloud ダッシュボードからデプロイする前に次を満たしてください。
* Strapi バージョン `4.8.2` 以上
* プロジェクトのデータベースは PostgreSQL と互換であること。外部 DB はサポート・推奨されませんが設定は可能です([高度なデータベース設定](/cloud/advanced/database))。
* ソースコードが
5. Strapi Cloud プロジェクトを設定します。
5.a. 次の情報を入力します。
| 設定名 | 説明 |
|--------------|---------------------------------------------------------------------------------------------------------|
| Display name | 選んだリポジトリ名が自動入力されますが、必要なら編集できます。 |
| Git branch | デプロイするブランチをドロップダウンから選びます。 |
| Deploy on push | 選択したブランチへの push で自動デプロイする場合はオン。オフの場合は手動で最新をデプロイします。 |
| Region | Strapi をホストするサーバーの地理的リージョン。米国(東)、欧州(西)、東南アジアから選べます。 |
:::note
Git ブランチと「Deploy on push」は後からプロジェクト設定で変更できます。ホスティングリージョンは**プロジェクト作成時のみ**選べます([プロジェクト設定](/cloud/projects/settings))。
:::
5.b. (任意)**Show advanced settings** で次を入力します。
| 設定名 | 説明 |
|--------------|---------------------------------------------------------------------------------------------------------|
| Base directory | リポジトリ内で Strapi アプリがあるディレクトリ名。モノレポや同一リポジトリに複数アプリがあるときに使用します。 |
| Environment variables | **Add variable** で Strapi の環境変数を追加します([環境変数](/cms/configurations/environment/))。Strapi アプリ直下の `.env` にも定義でき、Strapi Cloud でも利用されます。 |
| Node version | ドロップダウンで Node バージョンを選びます。既定はプロジェクトの Strapi に合うよう自動選択されます。手動で合わないバージョンを選ぶとビルドは失敗し、ビルドログに理由が出ます。 |
:::strapi 環境変数の利用
環境変数で Strapi Cloud 既定以外の外部データベースに接続できます(詳細は [データベース設定](/cms/configurations/database#environment-variables-in-database-configurations))。Strapi 既定の DB に戻す場合は `DATABASE_` で始まる環境変数を削除します(自動マイグレーションはありません)。
カスタムのメールプロバイダーもここで設定できます。Strapi Cloud 上のアプリでは Sendgrid が既定です([プロバイダー設定](/cms/features/email#providers))。
:::
## 請求情報の設定
:::strapi Free プランに請求ステップはありません
Free を選んだ場合、クレジットカード入力は求められず、このステップはスキップされます。
下のセクションのステップ 5 に進み、プロジェクト作成を完了してください。
:::
1. **Continue to billing** をクリックします。請求ページで支払い情報を入力し、請求内容を確認します。
2. *Payment method* でクレジットカードを追加します。このカードがアドオンや超過分などプロジェクト関連の課金に使われます。
3. *Billing information* に支払い・請求先住所を入力します。
4. *Invoice* を確認します。月額契約の場合、現在の請求サイクル残り日数に応じて日割りが入ります。*Discount code* を展開してコードを入力することもできます。
:::note
請求先に応じて税が加算されることがあります。
- EU / 英国: 有効な VAT ID があれば VAT は免除。なければ請求書に VAT が加算されます。
- 米国: 州と住所に基づき売上税が計算されます。
:::
5. **Subscribe** をクリックして Strapi Cloud プロジェクトの作成を完了します。
## プロジェクトのデプロイ
作成を確定すると *Project dashboard* に移り、作成と初回デプロイの進行を追跡できます。
デプロイ中でも [プロジェクト設定](/cloud/projects/settings) の一部を先に構成できます。
:::note
作成中にエラーが出ると、進行表示が止まりエラーメッセージが表示されます。失敗したステップの横に **Retry** が出るので、作成プロセスを再開できます。
:::
デプロイが成功すると、作成トラッカーがデプロイ一覧に置き換わり、クラウド上のアプリにアクセスできます。Strapi プロジェクトを共有する前に、最初の管理者ユーザーを作成してください。
## 次のステップ
Cloud ダッシュボードからデプロイできたら、次も試してください。
- 他のユーザーを [プロジェクトに招待](/cloud/projects/collaboration) する
- [デプロイ管理](/cloud/projects/deploys) で新しいデプロイの手順を読む
# Strapi Cloud - CLI deployment
Source: https://docs.strapi.io/cloud/getting-started/deployment-cli
# Project deployment with the Command Line Interface (CLI)
This is a step-by-step guide for deploying your project on Strapi Cloud for the first time, using the Command Line Interface.
:::prerequisites
Before you can deploy your Strapi application on Strapi Cloud using the Command Line Interface, you need to have the following prerequisites:
- Have a Google, GitHub or GitLab account.
- Have an already created Strapi project (see [Installing from CLI in the CMS Documentation](/cms/installation/cli)), stored locally. The project must be less than 100MB.
- Have available storage in your hard drive where the temporary folder of your operating system is stored.
:::
## Logging in to Strapi Cloud
1. Open your terminal.
2. Navigate to the folder of your Strapi project, stored locally on your computer.
3. Enter the following command to log into Strapi Cloud:
4. In the browser window that opens automatically, confirm that the code displayed is the same as the one written in the terminal message.
5. Still in the browser window, choose whether to login via Google, GitHub or GitLab. The window should confirm the successful login soon after.
## Deploying your project
1. From your terminal, still from the folder of your Strapi project, enter the following command to deploy the project:
2. Follow the progression bar in the terminal until confirmation that the project was successfully deployed with Strapi Cloud.
Deploying the project will create a new Strapi Cloud project on the Free plan.
### Automatically deploying subsequent changes
By default, when creating and deploying a project with the Cloud CLI, you need to manually deploy again all subsequent changes by running the corresponding `deploy` command everytime you make a change.
Another option is to enable automatic deployment through a git repository. To do so:
1. Host your code on a git repository, such as or .
2. Connect your Strapi Cloud project to the repository (see the _Connected repository_ setting in [Projects Settings > General](/cloud/projects/settings#general)).
3. Still in _Projects Settings > General_ tab, tick the box for the "Deploy the project on every commit pushed to this branch" setting. From now on, a new deployment to Strapi Cloud will be triggered any time a commit is pushed to the connected git repository.
:::note
Automatic deployment is compatible with all other deployment methods, so once a git repository is connected, you can trigger a new deployment to Strapi Cloud [from the Cloud dashboard](/cloud/projects/deploys), [from the CLI](/cloud/cli/cloud-cli#strapi-deploy), or by pushing new commits to your connected repository.
:::
## ⏩ What to do next?
Now that you have deployed your project via the Command Line Interface, we encourage you to explore the following ideas to have an even more complete Strapi Cloud experience:
- Visit the Cloud dashboard to follow [insightful metrics and information](/cloud/projects/overview) on your Strapi project.
- Check out the full [Command Line Interface documentation](/cloud/cli/cloud-cli) to learn about the other commands available.
# Project deployment
Source: https://docs.strapi.io/cloud/getting-started/deployment-options
# Project deployment with Strapi Cloud
You have 2 options to deploy your project with Strapi Cloud:
- either with the user interface (UI), meaning that you will perform all the actions directly on the Strapi Cloud dashboard,
- or using the Cloud Comment Line Interface (CLI), meaning that you will only interact with a terminal.
The guides below will guide you through all the steps for each of the deployment options.
# Strapi Cloud ドキュメントへようこそ
Source: https://docs.strapi.io/cloud/getting-started/intro
# Strapi Cloud ドキュメントへようこそ
Strapi Cloud ドキュメントには、Strapi Cloud アカウントとアプリケーションのセットアップ、デプロイ、更新、カスタマイズに関する情報がまとまっています。
:::strapi Strapi Cloud とは?
です。
:::
:::prerequisites
Strapi チームが推奨する典型的な流れは次のとおりです。
1. ローカルで Strapi アプリケーションを作成する(v4.8.2 以降)。
2. 必要に応じてプラグインや独自コードで拡張する。
3. Git プロバイダー(GitHub または GitLab)でコードベースをバージョン管理する。
4. Strapi Cloud にアプリケーションをデプロイする。
:::
Strapi Cloud ドキュメントは、プロダクト利用の流れに沿ったトピック順に構成されています。次のカードをクリックすると、主要なトピックと手順へ移動します。
:::strapi Strapi コミュニティへようこそ!
Strapi Cloud は、オープンソースでコミュニティ志向の Strapi の上に構築されています。Strapi チームはビジョンを共有し、コミュニティとともに Strapi の未来を形作りたいと考えています。そのため は公開されており、さまざまな知見がプロジェクトの方向づけに役立ちます。コミュニティの誰もがアイデアや意見を共有できます。
、、 に参加すれば、長年の経験と知識、コントリビューションをコミュニティ全体から得られます。
:::
# 請求と利用に関する情報
Source: https://docs.strapi.io/cloud/getting-started/usage-billing
# 請求と利用に関する情報
Strapi Cloud アカウントとプロジェクトの利用・請求に関する概要です。
Strapi Cloud には Free と、有料の Essential / Pro / Scale があります([料金ページ](https://strapi.io/pricing-cloud))。下表は主な機能と利用枠の整理です。
| 機能 | Free | Essential | Pro | Scale |
| -------------------------------- | ----- | --------- | --- | ----- |
| **データベースエントリ数** | 500 | 無制限* | 無制限* | 無制限* |
| **アセットストレージ** | 10GB | 50GB | 250GB | 1,000GB |
| **アセット帯域幅(月あたり)** | 10GB | 50GB | 500GB | 1,000GB |
| **API リクエスト(月あたり)** | 2,500 | 50,000 | 1,000,000 | 10,000,000 |
| | | | | |
| **バックアップ** | 該当なし | 該当なし | 週次 | 日次 |
| **カスタムドメイン** | 該当なし | 含まれる | 含まれる | 含まれる |
| **環境** | 該当なし | 該当なし | 0 含む(最大 99 まで追加) | 1 含む(最大 99 まで追加) |
| **メール(月あたり)** | 100 | 無制限* | 無制限* | 無制限* |
:::strapi 利用量と機能の補足
- 一般的な機能・利用量:
- データベースエントリ数は DB 内のエントリー件数です。
- アセットストレージはアセットが占める容量です。
- アセット帯域幅はアセット配信に使った転送量です。
- API リクエストは API へのリクエスト数です。GraphQL と REST を含み、CDN の帯域・ストレージとしてカウントされるメディアファイル向けリクエストは除きます。レスポンスの種類に関わらず、月間利用量に含まれます。
- Cloud 固有の機能:
- バックアップは Strapi Cloud プロジェクトの自動バックアップです(詳細は [バックアップ](/cloud/projects/settings#backups))。
- カスタムドメインは Strapi Cloud 用の独自ドメイン設定です([カスタムドメイン](/cloud/projects/settings#connecting-a-custom-domain))。
- 環境数は、既定の本番環境に加えてプランに含まれる追加環境の数です([環境](/cloud/projects/settings#environments))。
:::
:::caution Free プランは個人・非商用のみ
商用利用には次のようなものが含まれます。
- サイトでの決済の受け付け・処理
- サイトの作成・更新・ホストの対価としての報酬
- 商品・サービスの広告・宣伝・販売
- 第三者向け広告のホスト・配信
詳細は [Strapi Cloud-Legal](https://strapi.io/cloud-legal) を参照してください。
:::
:::info Free プランのスケールゼロとコールドスタート
Free プランでは、しばらくアクセスがないとプロジェクトが自動的にスケールダウンしてゼロになります。フロントエンドや API から再度アクセスすると、応答が返るまで数秒〜1 分ほどかかることがあります。
有料プランに上げるとスケールゼロとコールドスタートが無効になり、常にすぐ応答しやすくなります。
:::
## 環境の管理
環境は Strapi Cloud プロジェクトの隔離されたインスタンスです。すべてのプロジェクトに既定の本番環境があり、Pro または Scale ではプロジェクト設定の *Environments* タブから追加環境を構成できます([環境](/cloud/projects/settings#environments))。追加環境の数に上限はありません。
追加環境の利用上限は本番環境と同じです(例: Pro ならアセットストレージも 250GB まで。超過料金の扱いも本番と同様)。ただしアセット帯域と API 呼び出しは**プロジェクト単位**のため、環境を増やしてもこれらの枠自体は増えません。
## 請求
請求は Strapi Cloud プロジェクトの利用に基づきます。プロジェクトのプランとアドオンは請求サイクルに応じて月払いまたは年払い、超過分は月次請求です。利用量と請求はプロジェクト設定の *Billing & Usage* で確認できます。
### 税
米国・英国・EU の請求先住所では、地域の税が請求書に加算されることがあります。税額は請求先と VAT/Tax ID の状態に基づき、チェックアウトと請求書に表示されます。
VAT/Tax ID は [アカウントの請求](/cloud/account/account-billing) 設定で追加・更新できます。
### 超過利用(Overages)
:::caution
Free プランでは超過利用はできません。
:::
API リクエスト、アセット帯域、アセットストレージの上限を超えると、超過分に対する料金が発生します。
例: Pro のアセット帯域 500GB を超えた場合、現在の請求期間の終わりかプロジェクト削除時に超過分が課金されます。超過分の日割りはなく、全額が請求されます。
超過分の料金は月次で、次のレートが適用されます。
| 機能 | レート |
| --- | --- |
| **API リクエスト** | $1.50 / 2.5 万リクエスト |
| **アセット帯域** | $30.00 / 100GB |
| **アセットストレージ** | $0.60 / GB・月 |
### プロジェクトの停止(Suspension) {#project-suspension}
**Suspended** になる理由には、未払い請求、Free プラン上限の超過、Strapi Cloud の 違反などがあります。
停止中は管理パネルにアクセスできず、新しいデプロイも実行できません。ダッシュボードに理由を示すバナーが出ます。メールでも通知されます。
#### Free プランの上限超過による停止
Free で API リクエストまたはアセット帯域のいずれかを超過すると、翌月の枠がリセットされるまで停止します。
停止中は次のとおりです。
- 新しいデプロイは実行できない
- アプリケーションへのアクセスはブロックされる
- プロジェクト設定の変更はできない
すぐ再有効化するには有料プランへのアップグレードが必要です。
#### 請求トラブルによる停止
未払い請求があるとサブスクリプションが自動解約され、プロジェクトが停止します。
再有効化するには *Settings > Billing & Usage* で **Reactivate subscription** をクリックします。
:::warning
30 日以内に解決しないと、停止中のプロジェクトは削除され、データは完全に失われます。
:::
#### その他の理由による停止
未払い以外でサブスクリプション解約に至った場合など、自分で再有効化できないことがあります。メールの手順に従ってください。通知がない場合は [Strapi Support](mailto:support@strapi.io) に連絡してください。
### サブスクリプションの解約
Strapi Cloud のサブスクリプションをやめるには次のいずれかです。
- プロジェクトのサブスクリプションを Free プランに変更する([プランのダウングレード](/cloud/projects/settings#downgrading-to-another-plan))
- プロジェクトを完全に削除する([Strapi Cloud プロジェクトの削除](/cloud/projects/settings#deleting-a-strapi-cloud-project))
# Collaboration
Source: https://docs.strapi.io/cloud/projects/collaboration
# Collaboration on projects
Projects are created by a user via their Strapi Cloud account. Strapi Cloud users can share their projects to anyone else, so these new users can have access to the project dashboard and collaborate on that project, without the project owner to ever have to share their credentials.
Users invited to collaborate on a project, called maintainers, do not have the same permissions as the project owner. Contrary to the project owner, maintainers:
- Cannot share the project themselves to someone else
- Cannot delete the project from the project settings
- Cannot access the *Billing* section of project settings
## Sharing a project
To invite a new maintainer to collaborate on a project:
1. From the *Projects* page, click on the project of your choice to be redirected to its dashboard.
2. Click on the **Share** button located in the dashboard's header.
3. In the *Share [project name]* dialog, type the email address of the person to invite in the textbox. A dropdown indicating "Invite [email address]" should appear.
4. Click on the dropdown: the email address should be displayed in a purple box right below the textbox.
5. (optional) Repeat steps 3 and 4 to invite more people. Email addresses can only entered one by one but invites can be sent to several email addresses at the same time.
6. Click on the **Send** button.
New maintainers will be sent an email containing a link to click on to join the project. Once a project is shared, avatars representing the maintainers will be displayed in the project dashboard's header, next to the **Share** button, to see how many maintainers collaborate on that project and who they are.
:::tip
Avatars use GitHub, Google or GitLab profile pictures, but for pending users only initials will be displayed until the activation of the maintainer account. You can hover over an avatar to display the full name of the maintainer.
:::
## Managing maintainers
From the *Share [project name]* dialog accessible by clicking on the **Share** button of a project dashboard, projects owners can view the full list of maintainers who have been invited to collaborate on the project. From there, it is possible to see the current status of each maintainer and to manage them.
Maintainers whose full name is displayed are users who did activate their account following the invitation email. If however there are maintainers in the list whose email address is displayed, it means they haven't activated their accounts and can't access the project dashboard yet. In that case, a status should be indicated right next to the email address to explain the issue:
- Pending: the invitation email has been sent but the maintainer hasn't acted on it yet.
- Expired: the email has been sent over 72 hours ago and the invitation expired.
For Expired statuses, it is possible to send another invitation email by clicking on the **Manage** button, then **Resend invite**.
### Revoking maintainers
To revoke a maintainer's access to the project dashboard:
1. Click on the **Share** button in the project dashboard's header.
2. In the list of *People with access*, find the maintainer whose access to revoke and click on the **Manage** button.
3. Click on the **Revoke** button.
4. In the confirmation dialog, click again on the **Revoke** button.
The revoked maintainer will completely stop having access to the project dashboard.
:::note
Maintainers whose access to the project has been revoked do not receive any email or notification.
:::
# Deployments management
Source: https://docs.strapi.io/cloud/projects/deploys
# Deployments management
The creation of a new Strapi Cloud project automatically trigger the deployment of that project. After that, deployments can be:
- manually triggered whenever needed, [from the Cloud dashboard](#triggering-a-new-deployment) or [from the CLI](/cloud/cli/cloud-cli#strapi-deploy),
- or automatically triggered everytime a new commit is pushed to the branch, if the Strapi Cloud project is connected to a git repository and the "deploy on push" option is enabled (see [Project settings](/cloud/projects/settings#modifying-git-repository--branch)).
Ongoing deployments can also be [manually canceled](#cancelling-a-deployment) if needed.
## Triggering a new deployment
To manually trigger a new deployment for your project, click on the **Trigger deployment** button always displayed in the right corner of a project dashboard's header. This action will add a new card in the *Deployments* tab, where you can monitor the status and view the deployment logs live (see [Deploy history and logs](/cloud/projects/deploys-history)).
## Cancelling a deployment
If for any reason you want to cancel an ongoing and unfinished deployment:
1. Go to the *Deployment details* page of the latest triggered deployment (see [Accessing log details](/cloud/projects/deploys-history#accessing-deployment-details--logs)).
2. Click on the **Cancel deployment** button in the top right corner. The status of the deployment will automatically change to *Canceled*.
:::tip
You can also cancel a deployment from the *Deployments* tab which lists the deployments history. The card of ongoing deployment with the *Building* status will display a  button for cancelling the deployment.
:::
# Deployment history & logs
Source: https://docs.strapi.io/cloud/projects/deploys-history
# Deployment history and logs {#deploy-history-and-logs}
For each Strapi Cloud project, you can access the history of all deployments that occurred and their details including build and deployment logs. This information is available in the *Deployments* tab.
## Viewing the deployment history {#viewing-deploy-history}
In the *Deployments* tab is displayed a chronological list of cards with the details of all historical deployments for your project.
, with a direct link to your git provider, and commit message
- Deployment status:
- *Deploying*
- *Done*
- *Canceled*
- *Build failed*
- *Deployment failed*
- Last deployment time (when the deployment was triggered and the duration)
- Branch
## Accessing deployment details & logs
From the *Deployments* tab, you can hover a deployment card to make the  **Show details** button appear. Clicking on this button will redirect you to the *Deployment details* page which contains the deployment's detailed logs.
, with a direct link to your git provider, and commit message used for this deployment
- *Status*, which can be *Building*, *Deploying*, *Done*, *Canceled*, *Build failed*, or *Deployment failed*
- *Source*: the branch and commit message for this deployment
- *Duration*: the amount of time the deployment took and when it occurred
# Notifications
Source: https://docs.strapi.io/cloud/projects/notifications
# Notifications
The Notification center can be opened by clicking the bell icon in the top navigation of the Cloud dashboard.
It displays a list of the latest notifications for all your existing projects. Clicking on a notification card from the list will redirect you to the *Log details* page of the corresponding deployment (more information in [Deploy history & logs](/cloud/projects/deploys-history#accessing-deployment-details--logs)).
The following notifications can be listed in the Notifications center:
- *deployment completed*: when a deployment is successfully done.
- *Build failed*: when a deployment fails during the build stage.
- *deployment failed*: when a deployment fails during the deployment stage.
- *deployment triggered*: when a deployment is triggered by a new push to the connected repository. This notification is however not sent when the deployment is triggered manually.
:::note
All notifications older than 30 days are automatically removed from the Notification center.
:::
# プロジェクトの概要
Source: https://docs.strapi.io/cloud/projects/overview
# プロジェクトの概要
*Projects* ページには、Strapi Cloud のすべてのプロジェクトが一覧表示されます。ここからプロジェクトを管理し、対応するアプリケーションへアクセスできます。
各プロジェクトカードには次の情報が表示されます。
* プロジェクト名
* 本番環境の最後に成功したデプロイの日付
* プロジェクトの現在の状態:
* *Disconnected*(リポジトリが Strapi Cloud に未接続)
* *Suspended*(停止中。[プロジェクトの停止](/cloud/getting-started/usage-billing#project-suspension) を参照して再有効化)
* *Incompatible version*(Strapi Cloud と互換性のない Strapi バージョンを使用中)
各カードには メニューがあり、次の操作ができます。
* **Visit App**: アプリケーションを開く
* **Go to Deployments**: [*Deployment*](/cloud/projects/deploys) ページへ
* **Go to Settings**: [*Settings*](/cloud/projects/settings) ページへ
:::tip
ナビゲーションバーの * Product updates* で、最新機能と修正を確認できます。
:::
## プロジェクトのダッシュボードへアクセスする
*Projects* ページで任意のプロジェクトカードをクリックするとダッシュボードが開きます。プロジェクトと環境の詳細、デプロイ履歴、各種設定へのアクセスができます。
ヘッダーから次の操作ができます。
- **Share** でプロジェクトへの共同編集ユーザーを招待する([コラボレーション](/cloud/projects/collaboration))。すでに招待済みのユーザーはアイコンで表示されます 。
- **Settings** でプロジェクトと既存環境の設定を開く 。
- 表示する環境の選択、または新しい環境の追加 。
- 新しいデプロイの実行([デプロイの管理](/cloud/projects/deploys))とアプリへの訪問 。
ダッシュボードにはほかにも次があります。
- *Deployments* と *Runtime logs* タブ(デプロイ履歴は [デプロイ履歴とログ](/cloud/projects/deploys-history)、ランタイムログは [該当ページ](/cloud/projects/runtime-logs))
- 右側のボックスにプロジェクトと環境の詳細 。内容の例:
- API 呼び出し数
- アセットの帯域幅とストレージの現在の使用量
- ブランチ名と、ブランチ設定への **Manage**([Git リポジトリとブランチの変更](/cloud/projects/settings#modifying-git-repository--branch))
- ベースディレクトリ名
- Strapi のバージョン
- Strapi アプリの URL
# Runtime logs
Source: https://docs.strapi.io/cloud/projects/runtime-logs
# Runtime logs
From a chosen project's dashboard, the *Runtime logs* tab displays the live logs of the project.
:::note
- The *Runtime logs* are only accessible once the project is successfully deployed.
- Runtime logs are not live for projects on the Free plan and are reset each time the application is scaled to zero due to inactivity.
:::
# Project settings
Source: https://docs.strapi.io/cloud/projects/settings
# Project settings
From a chosen project's dashboard, the **Settings** button, located in the header, enables you to manage the configurations and settings for your Strapi Cloud project and its environments.
The settings' menu on the left side of the interface is separated into 2 categories: the settings for the entire project and the settings specific to any configured environment for the project.
## Project-level settings
There are 5 tabs available for the project settings:
- [*General*](#general),
- [*Environments*](#environments),
- [*Billing & Usage*](#billing--usage),
- [Plans](#plans),
- and [Invoices](#invoices).
### General
The *General* tab for the project-level settings enables you to check and update the following options for the project:
- *Basic information*, to see:
- the name of your Strapi Cloud project — used to identify the project on the Cloud Dashboard, Strapi CLI, and deployment URLs — and change it (see [Renaming project](#renaming-project)).
- the chosen hosting region for your Strapi Cloud project, meaning the geographical location of the servers where the project and its data and resources are stored. The hosting region is set at project creation (see [Project creation](/cloud/getting-started/deployment)) and cannot be modified afterwards.
- the project's metadata, including the Production app internal name and the Subscription ID, which can be useful for debugging & support purposes.
- *Strapi CMS license key*: to enable and use some CMS features directly on your Cloud project (see [Pricing page](https://strapi.io/pricing-self-hosted) to purchase a license).
- *Connected Git repository*: to change the repository and branch used for your project (see [Modifying git repository & branch](#modifying-git-repository--branch)). Also allows to enable/disable the "deploy on push" option.
- *Danger zone*, with:
- *Transfer ownership*: for the project owner to transfer the ownership of the Cloud project to an already existing maintainer (see [Transferring project ownership](#transferring-project-ownership)).
- *Delete project*: to permanently delete your Strapi Cloud project (see [Deleting Strapi Cloud project](#deleting-a-strapi-cloud-project)).
#### Renaming project
The project name is set at project creation (see [Project creation](/cloud/getting-started/deployment)) and can be modified afterwards via the project settings.
1. In the *Basic information* section of the *General* tab, click on the edit button.
2. In the dialog, write the new project name of your choice in the *Project name* textbox.
3. Click on the **Rename** button to confirm the project name modification.
#### Adding a CMS license key {#adding-cms-license-key}
A CMS license key can be added and connected to a Strapi Cloud project to unlock additional Strapi CMS features across all of the project’s environments. The CMS features that will be accessible via the license key depend on the type of license that was purchased. Please refer to the for more information and/or to purchase a license.
:::note
If you don't see the *Strapi CMS license key* section, it probably means that your subscription is a legacy one and does not support custom CMS licenses. It means that you already have one that is automatically included on your project.
:::
1. In the *Strapi CMS license key* section, click on the **Add license** button.
2. In the dialog, paste your license key in the field.
3. Click on the **Save & deploy** button for the changes to take effect.
To remove the Strapi CMS license from your Strapi Cloud project, you can click on the **Unlink license** button. This will also remove access and usage to the CMS features included in the previously added license.
:::note
The license key is applied to all the environments in the project.
:::
#### Modifying git repository & branch
The GitHub or GitLab repository, branch and base directory for a Strapi Cloud project are by default chosen at the creation of the project (see [Creating a project](/cloud/getting-started/deployment)). After the project's creation, via the project settings, it is possible to update the project repository or switch to another git provider.
:::caution
Updating the git repository could result in the loss of the project and its data, for instance if the wrong repository is selected or if the data schema between the old and new repository doesn't match.
:::
1. In the *Connected git repository* section of the *General* tab, click on the **Update repository** button. You will be redirected to another interface.
2. (optional) If you wish to not only update the repository but switch to another git provider, click on the **Switch Git provider** button at the top right corner of the interface. You will be redirected to the chosen git provider's authorization settings before getting back to the *Update repository* interface.
3. In the *Update repository* section, fill in the 2 available settings:
| Setting name | Instructions |
| --------------- | ------------------------------------------------------------------------ |
| Account | Choose an account from the drop-down list. |
| Repository | Choose a repository from the drop-down list. |
4. In the *Select Git branches* section, fill in the available settings for any of your environments. Note that the branch can be edited per environment via its own settings, see [General (environment)](#environments).
| Setting name | Instructions |
| --------------- | ------------------------------------------------------------------------ |
| Branch | Choose a branch from the drop-down list. |
| Base directory | Write the path of the base directory in the textbox. |
| Auto-deploy | Tick the box to automatically trigger a new deployment whenever a new commit is pushed to the selected branch. Untick it to disable the option. |
5. Click on the **Save & deploy** button for the changes to take effect.
#### Transferring project ownership {#transferring-project-ownership}
The ownership of the Strapi Cloud project can be transferred to another user, as long as they're a maintainer of the project. It can either be at the initiative of the current project owner, or can be requested by a project maintainer. Once the ownership is transferred, it is permanent until the new owner decides to transfer the ownership again to another maintainer.
:::prerequisites
For the ownership of a project to be transferred, the following requirements must be met:
- The project must be on a paid plan, with no currently expired card and/or unpaid bills.
- The maintainer must have filled their billing information.
- No already existing ownership transfer must be pending for the project.
Note that ownership transfers might fail when done the same day of subscription renewal (i.e. 1st of every month). If the transfer fails that day, but all prerequisites are met, you should wait a few hours and try again.
:::
1. In the *Danger zone* section of the *General* tab, click on the **Transfer ownership** button.
2. In the dialog:
- If you are the project owner: choose the maintainer who should be transferred the ownership by clicking on **...** > **Transfer ownership** associated with their name.
- If you are a maintainer: find yourself in the list and click on **...** > **Transfer ownership** associated with your name.
3. Confirm the transfer/request in the new dialog by clicking on the **Transfer ownership** button.
An email will be sent to both users. The person who needs to transfer the ownership or inherit it will have to click on the **Confirm transfer** button in the email. Once done, the previous owner will receive a confirmation email that the transfer has successfully been done.
:::tip
As long as the ownership transfer or request hasn't been confirmed, there is the option to cancel in the same dialog that the maintainer was chosen.
:::
:::note
Once the ownership transfer is done, the project will be disconnected from Strapi Cloud. As new owner, make sure to go to the *General* tab of project settings to reconnect the project.
:::
#### Deleting a Strapi Cloud project
You can delete any Strapi Cloud project, but it will be permanent and irreversible. Associated domains, deployments and data will be deleted and the subscription for the project will automatically be canceled.
1. In the *Danger zone* section of the *General* tab, click on the **Delete project** button.
2. In the dialog, select the reason for deleting your project.
3. Confirm the deletion of your project by clicking on the **Delete project** button.
### Environments {#environments}
The *Environments* tab allows to see all configured environments for the Strapi Cloud project, as well as to create new ones. Production is the default environment, which cannot be deleted. Other environments can be created (depending on the subscription plan for your project) to work more safely on isolated instances of your Strapi Cloud project (e.g. a staging environment where tests can be made before being available on production).
:::note
The billing cycle of additional environments you purchase will match the billing cycle of your plan.
:::
To create a new environment:
1. Click on the **Add a new environment** button.
2. In the setup step, fill in the available settings:
| Setting name | Instructions |
| ---------------- | ------------------------------------------------------------------------ |
| Environment name | (mandatory) Write a name for your project's new environment. |
| Git branch | (mandatory) Select the right branch for your new environment. |
| Base directory | Write the name of the base directory of your new environment. |
| Deploy on push | Tick this box to automatically trigger a deployment when changes are pushed to your selected branch. When disabled, you will need to manually deploy the latest changes. |
| Import variables | Tick the box to import variable names from an existing environment. Values will not be imported, and all variables will remain blank. |
3. Click **Confirm** to proceed to the checkout step.
4. Review the environment price, applicable taxes and proration adjustment.
5. Click on the **Add environment** button to create your project's new environment. You will then be redirected to your *Project dashboard* where you will be able to follow your new environment's creation and first deployment.
:::note
If an error occurs during the environment creation, the progress indicator will stop and display an error message. You will see a **Retry** button next to the failed step, allowing you to restart the creation process.
:::
### Billing & Usage
The *Billing & Usage* tab displays your next estimated payment, all information on the current subscription plan and a detailed summary of the project's usage. It also allows you to add new environments (please [refer to the documentation in the Environments section](#environments)) for your project.
Through this tab, you also have the possibility to:
- click the **Change** button to be redirected to the *Plans* tab, where you can change your subscription plan or billing cycle ([see related documentation](#plans)),
- click the **Edit** button in order to set a new payment method (see [related documentation](/cloud/account/account-billing)).
:::note
You can attach a dedicated card to your project by choosing the payment method directly from this page. In that way, you can manage your subscriptions with different cards.
:::
:::tip
In the Usage section of the *Billing & Usage* tab, you can see the current monthly usage of your project compared to the maximum usage allowed by your project's subscription. Use the arrows in the top right corner to see the project's usage for any chosen month.
Note also that if your usage indicates that another subscription plan would fit better for your project, a message will be displayed in the *Billing & Usage* tab to advise which plan you could switch to.
:::
### Plans
The *Plans* tab displays an overview of the available Strapi Cloud plans and allows you to change your current plan, or your billing cycle.
:::info
If your current plan is labeled as *legacy*, you will be able to sidegrade to a new plan (see [downgrade section](#downgrading-to-another-plan)). Once you sidegrade, you will no longer have access to your previous plan.
:::
#### Upgrading to another plan
Plan upgrades are immediate and can be managed, for each project, via the project settings.
To upgrade your current plan to a higher one:
1. In the *Plans* tab of your project settings, choose between monthly and yearly billing frequency, and click on the **Upgrade** button of the plan you want to upgrade to.
2. In the window that opens, review the payment details and terms of the upgrade.
a. (optional) Click the **Edit** button to select another payment method.
b. (optional) Click **I have a discount code**, enter your discount code in the field, and click on the **Apply** button.
3. Click on the **Upgrade to [plan name]** button to confirm the upgrade. The project will automatically be re-deployed.
#### Downgrading to another plan
Plan downgrades can be managed, for each project, via the project settings. Downgrades are, however, not immediately effective: the current plan will remain active until the end of the current billing period.
:::caution
Make sure to check the usage of your Strapi Cloud project before downgrading: if your current usage exceeds the limits of the lower plan, you are taking the risk of getting charged for overages. You may also lose access to some features: for example, downgrading to the Essential plan would result in the loss of all your project's backups. Please refer to [Information on billing & usage](/cloud/getting-started/usage-billing) for more information.
Note also that you cannot downgrade if you have additional paid environments. You will first need to delete all additional environments that were not included in the base price of you plan (see [Resetting & Deleting environment](#resetting--deleting-environment)) before you can schedule a downgrade. When downgrading from Scale to Pro, the additional included environment will automatically be deleted when the downgrade takes effect.
You cannot downgrade to the Free plan if a GitHub organization repository is connected to the project. To downgrade, first switch to a personal repository in the [Connected Git repository](#modifying-git-repository--branch) settings.
:::
To downgrade your current plan to a lower one:
1. In the *Plans* tab of your project settings, choose between monthly and yearly billing frequency and click on the **Downgrade** button of the plan you want to downgrade to.
2. In the window that opens, review the terms of the downgrade.
3. Click on the **Downgrade** button to confirm the downgrade. The project will automatically be re-deployed.
:::tip
Downgrades are effective at the end of the current billing period. Whilst the change is pending, you can cancel the scheduled downgrade and stay on your current plan.
:::
#### Changing billing cycle
You can switch your project's billing cycle between monthly and yearly billing at any time. While project plans and addons can either be billed monthly or yearly depending on your billing cycle, overages are always billed monthly.
To change your billing cycle:
1. In the *Plans* tab of your project settings, use the toggle at the top of the plans section to switch between monthly and yearly billing.
2. Click the **Switch to [monthly/yearly] billing** button of your current plan.
3. In the window that opens, review the terms of the billing cycle change.
4. Click **Confirm switch** to confirm the change.
:::note
When switching from yearly to monthly billing, your plan will remain on its yearly cycle until your next renewal date. Whilst the change is pending, you can cancel the scheduled change and stay on your current billing cycle. When switching from monthly to yearly, however, the change is immediate.
:::
### Invoices
The *Invoices* tab displays the full list of invoices for your Strapi Cloud project as well as their status. No invoice is issued for the Free plan.
:::strapi Invoices are also available in your profile settings.
In the *Profile > Invoices* tab, you will find the complete list of invoices for all your projects. Feel free to check the [dedicated documentation](/cloud/account/account-billing#account-invoices).
:::
## Environment-level settings
In the project's environments' settings, you first need to select the environment whose settings you would like to configure, using the dropdown. Depending on the chosen environment, there are 3 to 4 tabs available:
- [*Configuration*](#configuration),
- [*Backups*](#backups), which are only available for the production environment,
- [*Domains*](#domains),
- and [*Variables*](#variables).
### Configuration
The *Configuration* tab for the environment-level settings enables you to check and update the following options for the project:
- *Basic information*, to see:
- the name of your Strapi Cloud project's environment. The environment name is set when it is created and cannot be modified afterwards.
- the Node version of the environment: to change the Node version of the project (see [Modifying Node version](#modifying-node-version)).
- the app's internal name for the environment, which can be useful for debug & support purposes.
- *Connected branch*: to change the branch of the GitHub repository used for your environment (see [Editing Git branch](#editing-git-branch)). Also allows to enable/disable the "deploy on push" option.
- *Environment data*: to transfer data from another environment within the same project (see [Transferring data between environments](#transferring-data-between-environments)).
- *Danger zone*: to reset or permanently delete your Strapi Cloud project's environment (see [Resetting & Deleting environment](#resetting--deleting-environment)).
#### Modifying Node version
The environment's Node version is based on the one chosen at the creation of the project (see [Creating a project](/cloud/getting-started/deployment)), through the advanced settings. It is possible to switch to another Node version afterwards, for any environment.
1. In the *Basic information* section of the *Configuration* tab, click on the *Node version*'s edit button.
2. Using the *Node version* drop-down in the dialog, click on the version of your choice.
3. Click on **Save**, or **Save & deploy** if you want the changes to take effect immediately.
:::tip
Ensure the Node version configured in your Strapi project matches the Node version shown in your project’s dashboard before deploying.
:::
#### Editing Git branch
1. In the *Edit branch* dialog, edit the available settings. Note that the branch can be edited for all environments at the same time via the project settings, see [General](#general).
| Setting name | Instructions |
| --------------- | ------------------------------------------------------------------------ |
| Selected branch | (mandatory) Choose a branch from the drop-down list. |
| Base directory | Write the path of the base directory in the textbox. |
| Deploy the project on every commit pushed to this branch | Tick the box to automatically trigger a new deployment whenever a new commit is pushed to the selected branch. Untick it to disable the option. |
2. Click on the **Save & deploy** button for the changes to take effect.
#### Transferring data between environments {#transferring-data-between-environments}
The data transfer feature allows you to transfer the entire CMS content (database and assets) from one environment to another within the same Strapi Cloud project. This is useful for testing changes in a secondary environment with up-to-date production data, or for preparing and staging content in a secondary environment before taking it to production.
Transferring data between environments currently comes with the following limitations:
- You can only transfer toward a secondary environment (not the production environment).
- Only project owners can initiate and manage ongoing transfers.
- Transfers cannot be initiated on projects that are suspended.
:::caution Data transfers are destructive
Transferring data to an environment will permanently overwrite all existing data and assets in the target environment. The source environment's data remains unaffected, and its CMS can be accessed during the transfer. Environment settings (such as variables and domains) are not affected by the transfer.
:::
To transfer data to a secondary environment:
1. Create and deploy both the source and target [environments](#environments).
2. In the *Environment data* section of the *Configuration* tab, click on the **Import data** button.
3. In the modal that opens, select the source environment from the drop-down list. Only fully created and deployed environments are available as sources.
4. Click on **Import data** to proceed, and follow the steps to confirm the transfer.
5. Once initiated, you will be redirected to the environment's dashboard where you can monitor the transfer's progress. Once the transfer is completed, the dashboard will refresh, showing both the ongoing and historic deployments.
:::note
The CMS of the target environment will be inaccessible whilst the transfer is ongoing. You can cancel an ongoing transfer, but this will leave the target environment empty. If an error occurs during the transfer, you will have the option to retry or cancel.
:::
#### Resetting & Deleting environment
You can reset or delete any additional environment of your Strapi Cloud project, but it will be permanent and irreversible. The default, production environment, can however neither be reset nor deleted.
##### Resetting an environment
Resetting an environment deletes all environments data and resets the variables to their default. To do so:
1. In the *Danger zone* section of the *Configuration* tab, click on the **Reset environment** button.
2. In the dialog that opens, click on the **Continue** button to confirm the environment reset.
3. Fill in the available fields to reset the environment:
| Setting name | Instructions |
| --------------- | ------------------------------------------------------------------------ |
| Environment name | (mandatory) Write a name for your project's new environment. |
| Git branch | (mandatory) Choose a branch from the drop-down list. |
| Base directory | Write the path of the base directory in the textbox. |
| Import variables | Tick the box to import variable names from an existing environment. Values will not be imported, and all variables will remain blank. |
| Auto-deploy | Deploy the project on every commit pushed to this branch. Tick the box to automatically trigger a new deployment whenever a new commit is pushed to the selected branch. Untick it to disable the option. |
4. Click on the **Reset** button.
##### Deleting an environment
1. In the *Danger zone* section of the *Configuration* tab, click on the **Delete environment** button.
2. Write in the textbox your *Environment name*.
3. Click on the **Delete environment** button to confirm the deletion.
### Backups {#backups}
The *Backups* tab informs you of the status and date of the latest backup of your Strapi Cloud projects. The databases associated with all existing Strapi Cloud projects are indeed automatically backed up (weekly for Pro plans and daily for Scale plans). Backups are retained for a 28-day period. Additionally, you can create a single manual backup.
:::note Notes
- The backup feature is not available for Strapi Cloud projects on the Free or Essential plans. You will need to upgrade to the Pro or Scale plan to enable automatic backups and access the manual backup option.
- Backups include only the database of your default Production environment. Assets uploaded to your project and databases from any secondary environments are not included.
- The manual backup option becomes available shortly after the project’s first successful deployment.
:::
:::tip
For projects created before the release of the Backup feature in October 2023, the first backup will automatically be triggered with the next deployment of the project.
:::
#### Creating a manual backup
To create a manual backup, in the *Backups* section, click on the **Create backup** button.
The manual backup should start immediately, and restoration or creation of other backups will be disabled until the backup is complete.
:::caution
When creating a new manual backup, any existing manual backup will be deleted. You can only have one manual backup at a time.
:::
#### Restoring a backup
If you need to restore a backup of your project:
1. In the *Backups* section, click on the **Restore backup** button.
2. In the dialog, choose one of the available backups (automatic or manual) of your project in the *Choose backup* drop-down.
3. Click on the **Restore** button of the dialog. Once the restoration is finished, your project will be back to the state it was at the time of the chosen backup. You will be able to see the restoration timestamp and the backup restored in the *Backups* tab.
4. The timestamp of the last completed restoration will be displayed to help you track when the project was last restored.
#### Downloading a backup
If you need to download a backup of your project:
1. In the *Backups* section, click on the **Download backup** button.
2. In the dialog, choose one of the available backups (automatic or manual) of your project in the *Choose backup* drop-down.
3. Click on the **Download** button of the dialog to download the chosen backup's archive file in `.sql` format.
:::note
The backup file will include only the database of your default Production environment. It will not include assets or any other environment databases.
:::
### Domains
The *Domains* tab enables you to manage domains and connect new ones.
All existing domains for your Strapi Cloud project are listed in the *Domains* tab. For each domain, you can:
- see its current status:
- Active: the domain is currently confirmed and active
- Pending: the domain transfer is being processed, waiting for DNS changes to propagate
- Failed: the domain change request did not complete as an error occurred
- click the edit button to access the settings of the domain
- click the delete button to delete the domain
#### Connecting a custom domain
Default domain names are made of 2 randomly generated words followed by a hash. They can be replaced by any custom domain of your choice.
:::note
Custom domains are not available on the Free plan. Downgrading to the Free plan will result in the application domain's being restored to the default one.
:::
1. Click the **Connect new domain** button.
2. In the window that opens, fill in the following fields:
| Setting name | Instructions |
| ------------------------- | ------------------------------------------------------------------------- |
| Domain name | Type the new domain name (e.g. *custom-domain-name.com*) |
| Hostname | Type the hostname (i.e. address end-users enter in web browser, or call through APIs). |
| Target | Type the target (i.e. actual address where users are redirected when entering hostname). |
| Set as default domain | Tick the box to make the new domain the default one. |
3. Click on **Save & deploy** for the changes to take effect.
:::tip
To finish setting up your custom domain, in the settings of your domain registrar or hosting platform, please add the Target value (e.g., `proud-unicorn-123456af.strapiapp.com`) as a CNAME alias to the DNS records of your domain.
:::
:::info Custom domains and assets
When using custom domains, these domains do not apply to the URLs of uploaded assets. Uploaded assets keep the Strapi Cloud project-based URL.
This means that, if your custom domain is hosted at `https://my-custom-domain.com` and your Strapi Cloud project name is `my-strapi-cloud-instance`, API calls will still return URLs such as `https://my-strapi-cloud-instance.media.strapiapp.com/example.png`.
Media library queries over REST or GraphQL always return the project media domain on Strapi Cloud. If you move from a self-hosted project, media URLs will no longer match your own domain or CDN. Plan to use the absolute URLs returned by the API, or adjust your frontend to allow the Strapi Cloud media domain (see [Cloud Fundamentals](/cloud/cloud-fundamentals) for more details).
:::
### Variables
Environment variables (more information in the [CMS Documentation](/cms/configurations/environment)) are used to configure the environment of your Strapi application, such as the database connection.
In the *Variables* tab are listed both the default and custom environment variables for your Strapi Cloud project. Each variable is composed of a *Name* and a *Value*.
#### Managing environment variables
Hovering on an environment variable, either default or custom, displays the following available options:
- **Show value** to replace the `*` characters with the actual value of a variable.
- **Copy to clipboard** to copy the value of a variable.
- **Actions** to access the Edit and Delete buttons.
- When editing a default variable, the *Name* cannot be modified and the *Value* can only be automatically generated using the Generate value button. Don't forget to **Save**, or **Save & deploy** if you want the changes to take effect immediately.
- When editing a custom variable, both the *Name* and *Value* can be modified by writing something new or by using the Generate value button. Don't forget to **Save**, or **Save & deploy** if you want the changes to take effect immediately.
- When deleting a variable, you will be asked to confirm by selecting **Save**, or **Save & deploy** if you want the changes to take effect immediately.
:::tip
Use the search bar to find more quickly an environment variable in the list!
:::
#### Creating custom environment variables
Custom environment variables can be created for the Strapi Cloud project. Make sure to redeploy your project after creating or editing an environment variable.
1. In the *Custom environment variables* section, click on the **Add variable** button.
2. Write the *Name* and *Value* of the new environment variable in the same-named fields. Alternatively, you can click on the icon to generate automatically the name and value.
3. (optional) Click on **Add another** to directly create one or more other custom environment variables.
4. Click on the **Save** button to confirm the creation of the custom environment variables. To apply your changes immediately, click on **Save & deploy**.
# Admin panel customization
Source: https://docs.strapi.io/cms/admin-panel-customization
# Admin panel customization
The **front-end part of Strapi** is called the admin panel. The admin panel presents a graphical user interface to help you structure and manage the content that will be accessible through the Content API. To get an overview of the admin panel, please refer to the [Getting Started > Admin panel](/cms/features/admin-panel) page.
From a developer point of view, Strapi's admin panel is a React-based single-page application that encapsulates all the features and installed plugins of a Strapi application.
Admin panel customization is done by tweaking the code of the `src/admin/app` file or other files included in the `src/admin` folder (see [project structure](/cms/project-structure)). By doing so, you can:
- Customize some parts of the admin panel to better reflect your brand identity (logos, favicon) or your language,
- Replace some other parts of the admin panel, such as the Rich text editor and the bundler,
- Extend the theme or the admin panel to add new features or customize the existing user interface.
:::strapi Plugins and Admin Panel API
In addition to supported customizations detailed in this section, you can go further and create plugins that tap into the [Admin Panel API](/cms/plugins-development/admin-panel-api).
:::
## General considerations
:::prerequisites
Before updating code to customize the admin panel:
- Rename the default `app.example.tsx|js` file into `app.ts|js`.
- Create a new `extensions` folder in `/src/admin/`.
- If you want to see your changes applied live while developing, ensure the admin panel server is running (it's usually done with the `yarn develop` or `npm run develop` command if you have not changed the default [host, port, and path](/cms/configurations/admin-panel#admin-panel-server) of the admin panel).
:::
Most basic admin panel customizations will be done in the `/src/admin/app` file, which includes a `config` object.
Any file used by the `config` object (e.g., a custom logo) should be placed in a `/src/admin/extensions/` folder and imported inside `/src/admin/app.js`.
This will replace the folder's content located at `./build`. Visit
## Basic example
The following is an example of a basic customization of the admin panel:
:::strapi Detailed examples in the codebase
* You can see the full translation keys, for instance to change the welcome message, [on GitHub](https://github.com/strapi/strapi/blob/develop/packages/core/admin/admin/src/translations).
* Light and dark colors are also found [on GitHub](https://github.com/strapi/design-system/tree/main/packages/design-system/src/themes).
:::
# Admin panel bundlers
Source: https://docs.strapi.io/cms/admin-panel-customization/bundlers
# Admin panel bundlers
Strapi's [admin panel](/cms/admin-panel-customization) is a React-based single-page application that encapsulates all the features and installed plugins of a Strapi application. 2 different bundlers can be used with your Strapi 5 application, [Vite](#vite) (the default one) and [webpack](#webpack). Both bundlers can be configured to suit your needs.
:::info
For simplification, the following documentation mentions the `strapi develop` command, but in practice you will probably use its alias by running either `yarn develop` or `npm run develop` depending on your package manager of choice.
:::
## Vite
In Strapi 5,
## Webpack
In Strapi 5, the default bundler is Vite. To use
# Admin panel extension
Source: https://docs.strapi.io/cms/admin-panel-customization/extension
# Admin panel extension
Strapi's [admin panel](/cms/admin-panel-customization) is a React-based single-page application that encapsulates all the features and installed plugins of a Strapi application. If the [customization options](/cms/admin-panel-customization#available-customizations) provided by Strapi are not enough for your use case, you will need to extend Strapi's admin panel.
Extending Strapi's admin panel means leveraging its React foundation to adapt and enhance the interface and features according to the specific needs of your project, which might imply creating new components or adding new types of fields.
There are 2 use cases where you might want to extend the admin panel:
| Approach | Scope | Entry point | Docs |
|---|---|---|---|
| Local extension | One Strapi project | `/src/admin/app.(js\|ts)` and `/src/admin/extensions/` | [Admin panel customization](/cms/admin-panel-customization) |
| Plugin extension | Any project that installs your plugin | `[plugin-name]/admin/src/index.(js\|ts)` | [Admin Panel API overview](/cms/plugins-development/admin-panel-api) |
- As a Strapi plugin developer, you want to develop a Strapi plugin that extends the admin panel **everytime it's installed in any Strapi application**.
👉 This can be done by taking advantage of the [Admin Panel API for plugins](/cms/plugins-development/admin-panel-api), which lets you add navigation links and settings sections, inject React components into predefined areas, manage state with Redux, extend the Content Manager's Edit and List views, and more.
- As a Strapi developer, you want to develop a unique solution for a Strapi user who only needs to extend a specific instance of a Strapi application.
👉 This can be done by directly updating the `/src/admin/app` file, which can import any file located in `/src/admin/extensions`.
## When to consider a plugin instead
Starting with a direct customization in `/src/admin/app` is the right default for project-specific needs. Consider moving to a plugin-based approach when one or more of these signals appear:
- You are duplicating the same admin customization across several Strapi projects.
- You want to version and distribute the extension — either internally or through the .
- You need stronger automated testing independent from a single project codebase.
- Multiple teams need shared ownership and release management for the same extension.
For a full introduction to plugin development, see [Developing Strapi plugins](/cms/plugins-development/developing-plugins).
:::strapi Additional resources
* If you're looking for ways of replacing the default Rich text editor, refer to the [corresponding page](/cms/admin-panel-customization/wysiwyg-editor).
* To understand how plugins integrate with the Strapi admin panel, start with the [Admin Panel API overview](/cms/plugins-development/admin-panel-api).
:::
# Favicon
Source: https://docs.strapi.io/cms/admin-panel-customization/favicon
# Favicon
Strapi's [admin panel](/cms/admin-panel-customization) displays its branding on various places, including the [logo](/cms/admin-panel-customization/logos) and the favicon. Replacing these images allows you to match the interface and application to your identity.
There are 2 approaches to replacing the favicon:
* Replace the `favicon.png` file at the root of a Strapi project
* Edit the [`strapi::favicon` middleware configuration](/cms/configurations/middlewares#favicon) with the following code:
```js title="/config/middlewares.js"
// …
{
name: 'strapi::favicon',
config: {
path: 'my-custom-favicon.png',
},
},
// …
```
Once done, rebuild, launch and revisit your Strapi app by running `yarn build && yarn develop` in the terminal.
:::caution
Make sure that the cached favicon is cleared. It can be cached in your web browser and also with your domain management tool like Cloudflare's CDN.
:::
# Homepage customization
Source: https://docs.strapi.io/cms/admin-panel-customization/homepage
# Homepage customization
The
:::note The API requires Strapi 5.13+
The `app.widgets.register` API only works with Strapi 5.13 and above. Trying to call the API with older versions of Strapi will crash the admin panel.
Plugin developers who want to register widgets should either:
- set `^5.13.0` as their `@strapi/strapi` peerDependency in their plugin `package.json`. This peer dependency powers the Marketplace's compatibility check.
- or check if the API exists before calling it:
```js
if ('widgets' in app) {
// proceed with the registration
}
```
The peerDependency approach is recommended if the whole purpose of the plugin is to register widgets. The second approach makes more sense if a plugin wants to add a widget but most of its functionality is elsewhere.
:::
#### Widget API reference
The `app.widgets.register()` method can take either a single widget configuration object or an array of configuration objects. Each widget configuration object can accept the following properties:
| Property | Type | Description | Required |
|-------------|------------------------|-------------------------------------------------------|----------|
| `icon` | `React.ComponentType` | Icon component to display beside the widget title | Yes |
| `title` | `MessageDescriptor` | Title for the widget with translation support | Yes |
| `component` | `() => Promise
:::tip
For simplicity, the example below uses data fetching directly inside a useEffect hook. While this works for demonstration purposes, it may not reflect best practices in production.
For more robust solutions, consider alternative approaches recommended in the [React documentation](https://react.dev/learn/build-a-react-app-from-scratch#data-fetching). If you're looking to integrate a data fetching library, we recommend using [TanStackQuery](https://tanstack.com/query/v3/).
:::
**Data management**:

The green box above represents the area where the user’s React component (from `widget.component` in the [API](#widget-api-reference)) is rendered. You can render whatever you like inside of this box. Everything outside that box is, however, rendered by Strapi. This ensures overall design consistency within the admin panel. The `icon`, `title`, and `link` (optional) properties provided in the API are used to display the widget.
#### Widget helper components reference
Strapi provides several helper components to maintain a consistent user experience across widgets:
| Component | Description | Usage |
|------------------|-----------------------------------------------------|--------------------------------------|
| `Widget.Loading` | Displays a loading spinner and message | When data is being fetched |
| `Widget.Error` | Displays an error state | When an error occurs |
| `Widget.NoData` | Displays when no data is available | When the widget has no data to show |
| `Widget.NoPermissions` | Displays when user lacks required permissions | When the user cannot access the widget |
These components help maintain a consistent look and feel across different widgets.
You could render these components without children to get the default wording: `
))}
);
};
```
The following file defines a custom controller that counts all content-types:
```js title="src/plugins/content-metrics/server/src/controllers/metrics.js"
'use strict';
module.exports = ({ strapi }) => ({
async getContentCounts(ctx) {
try {
// Get all content types
const contentTypes = Object.keys(strapi.contentTypes)
.filter(uid => uid.startsWith('api::'))
.reduce((acc, uid) => {
const contentType = strapi.contentTypes[uid];
acc[contentType.info.displayName || uid] = 0;
return acc;
}, {});
// Count entities for each content type
for (const [name, _] of Object.entries(contentTypes)) {
const uid = Object.keys(strapi.contentTypes)
.find(key =>
strapi.contentTypes[key].info.displayName === name || key === name
);
if (uid) {
// Using the count() method from the Document Service API
const count = await strapi.documents(uid).count();
contentTypes[name] = count;
}
}
ctx.body = contentTypes;
} catch (err) {
ctx.throw(500, err);
}
}
});
```
The following file ensures that the metrics controller is reachable at a custom `/count` route:
```js title="src/plugins/content-metrics/server/src/routes/index.js"
'content-api': {
type: 'content-api',
routes: [
{
method: 'GET',
path: '/count',
handler: 'metrics.getContentCounts',
config: {
policies: [],
},
},
],
},
};
```
))}
);
};
```
The following file defines a custom controller that counts all content-types:
```js title="src/plugins/content-metrics/server/src/controllers/metrics.js"
'use strict';
module.exports = ({ strapi }) => ({
async getContentCounts(ctx) {
try {
// Get all content types
const contentTypes = Object.keys(strapi.contentTypes)
.filter(uid => uid.startsWith('api::'))
.reduce((acc, uid) => {
const contentType = strapi.contentTypes[uid];
acc[contentType.info.displayName || uid] = 0;
return acc;
}, {});
// Count entities for each content type using Document Service
for (const [name, _] of Object.entries(contentTypes)) {
const uid = Object.keys(strapi.contentTypes)
.find(key =>
strapi.contentTypes[key].info.displayName === name || key === name
);
if (uid) {
// Using the count() method from Document Service instead of strapi.db.query
const count = await strapi.documents(uid).count();
contentTypes[name] = count;
}
}
ctx.body = contentTypes;
} catch (err) {
ctx.throw(500, err);
}
}
});
```
The following file ensures that the metrics controller is reachable at a custom `/count` route:
```js title="src/plugins/content-metrics/server/src/routes/index.js"
'content-api': {
type: 'content-api',
routes: [
{
method: 'GET',
path: '/count',
handler: 'metrics.getContentCounts',
config: {
policies: [],
},
},
],
},
};
```
# Locales & translations
Source: https://docs.strapi.io/cms/admin-panel-customization/locales-translations
# Locales & translations
The Strapi [admin panel](/cms/admin-panel-customization) ships with English strings and supports adding other locales so your editorial team can work in their preferred language. Locales determine which languages appear in the interface, while translations provide the text displayed for each key in a locale.
This guide targets project maintainers customizing the admin experience from the application codebase. All examples modify the configuration exported from `/src/admin/app` file, which Strapi loads when the admin panel builds. You'll learn how to declare additional locales and how to extend Strapi or plugin translations when a locale is missing strings.
## Defining locales
To update the list of available locales in the admin panel, set the `config.locales` array in `src/admin/app` file:
:::note Notes
- The `en` locale cannot be removed from the build as it is both the fallback (i.e. if a translation is not found in a locale, the `en` will be used) and the default locale (i.e. used when a user opens the administration panel for the first time).
- The full list of available locales is accessible on
A plugin's key/value pairs are declared independently in the plugin's files at `/admin/src/translations/[language-name].json`. These key/value pairs can similarly be extended in the `config.translations` key by prefixing the key with the plugin's name (i.e. `[plugin name].[key]: 'value'`) as in the following example:
If you need to ship additional translation JSON files—for example to organize large overrides or to support a locale not bundled with Strapi—place them in the `/src/admin/extensions/translations` folder and ensure the locale code is listed in `config.locales`.
:::tip Rebuild the admin
Translation changes apply when the admin rebuilds. If updates don’t show, re-run your dev server or rebuild the admin to refresh bundled translations.
:::
# Logos
Source: https://docs.strapi.io/cms/admin-panel-customization/logos
# Logos
Strapi's [admin panel](/cms/admin-panel-customization) displays its branding on both the login screen and in the main navigation. Replacing these images allows you to match the interface to your identity. The present page shows how to override the two logo files via the admin panel configuration. If you prefer uploading them directly in the UI, see [Customizing the logo](/cms/features/admin-panel#customizing-the-logo).
The Strapi admin panel displays a logo in 2 different locations, represented by 2 different keys in the admin panel configuration:
| Location in the UI | Configuration key to update |
| ---------------------- | --------------------------- |
| On the login page | `config.auth.logo` |
| In the main navigation | `config.menu.logo` |
:::note
Logos uploaded via the admin panel supersede any logo set through the configuration files.
:::
### Logos location in the admin panel
The logo handled by `config.auth.logo` logo is only shown on the login screen:

The logo handled by `config.menu.logo` logo is located in the main navigation at the top left corner of the admin panel:

### Updating logos
To update the logos, put image files in the `/src/admin/extensions` folder, import these files in `src/admin/app` and update the corresponding keys as in the following example:
:::note
There is no size limit for image files set through the configuration files.
:::
# Theme extension
Source: https://docs.strapi.io/cms/admin-panel-customization/theme-extension
# Theme extension
Strapi's [admin panel](/cms/admin-panel-customization) can be displayed either in light or dark mode (see [profile setup](/cms/getting-started/setting-up-admin-panel#setting-up-your-administrator-profile)), and both can be extended through custom theme settings.
To extend the theme, use either:
- the `config.theme.light` key for the Light mode
- the `config.theme.dark` key for the Dark mode
:::strapi Strapi Design System
The default
# Customizing the rich text editor
Source: https://docs.strapi.io/cms/admin-panel-customization/wysiwyg-editor
# Change the default rich text editor
Strapi's [admin panel](/cms/admin-panel-customization) comes with a built-in rich text editor. To change the default editor, several options are at your disposal:
- You can install a third-party plugin, such as one for CKEditor, by visiting .
- You can create your own plugin to create and register a fully custom WYSIWYG field (see [custom fields documentation](/cms/features/custom-fields)).
:::tip Next steps
When evaluating editors, start with a plugin from the Marketplace for a quick trial, then consider a custom field if you need deeper integration (schema, validation, or custom toolbar behavior).
:::
# Strapi Client
Source: https://docs.strapi.io/cms/api/client
# Strapi Client
The Strapi Client library simplifies interactions with your Strapi back end, providing a way to fetch, create, update, and delete content. This guide walks you through setting up the Strapi Client, configuring authentication, and using its key features effectively.
## Getting Started
:::prerequisites
- A Strapi project has been created and is running. If you haven't set one up yet, follow the [Quick Start Guide](/cms/quick-start) to create one.
- You know the URL of the Content API of your Strapi instance (e.g., `http://localhost:1337/api`).
:::
### Installation
To use the Strapi Client in your project, install it as a dependency using your preferred package manager:
### Basic configuration
To start interacting with your Strapi back end, initialize the Strapi Client and set the base API URL:
The `baseURL` must include the protocol (`http` or `https`). An invalid URL will throw an error `StrapiInitializationError`.
### Authentication
The Strapi Client supports different authentication strategies to access protected resources in your Strapi back end.
If your Strapi instance uses [API tokens](/cms/features/api-tokens), configure the Strapi Client as follows:
```js
const client = strapi({
baseURL: 'http://localhost:1337/api',
auth: 'your-api-token-here',
});
```
This allows your requests to include the necessary authentication credentials automatically.
If the token is invalid or missing, the client will throw an error during initialization `StrapiValidationError`.
## API Reference
The Strapi Client provides the following key properties and methods for interacting with your Strapi back end:
| Parameter | Description |
| ----------| -------------------------------------------------------------------------------------------- |
| `baseURL` | The base API URL of your Strapi back end. |
| `fetch()` | A utility method for making generic API requests similar to the native fetch API. |
| `collection()` | Manages collection-type resources (e.g., blog posts, products). |
| `single()` | Manages single-type resources (e.g., homepage settings, global configurations). |
| `files()` | Enables upload, retrieve and management of files directly to/from the Strapi Media Library. |
### General purpose fetch
The Strapi Client provides access to the underlying JavaScript `fetch` function to make direct API requests. The request is always relative to the base URL provided during client initialization:
```js
const result = await client.fetch('articles', { method: 'GET' });
```
### Working with collection types
Collection types in Strapi are entities with multiple entries (e.g., a blog with many posts). The Strapi Client provides a `collection()` method to interact with these resources, with the following methods available:
| Parameter | Description |
| ----------| -------------------------------------------------------------------------------------------- |
| `find(queryParams?)` | Fetch multiple documents with optional filtering, sorting, or pagination. |
| `findOne(documentID, queryParams?)` | Retrieve a single document by its unique ID. |
| `create(data, queryParams?)` | Create a new document in the collection. |
| `update(documentID, data, queryParams?)` | Update an existing document. |
| `delete(documentID, queryParams?)` | Update an existing document. |
**Usage examples:**
### Working with single types
Single types in Strapi represent unique content entries that exist only once (e.g., the homepage settings or site-wide configurations). The Strapi Client provides a `single()` method to interact with these resources, with the following methods available:
| Parameter | Description |
| ----------| -------------------------------------------------------------------------------------------- |
| `find(queryParams?)` | Fetch the document. |
| `update(documentID, data, queryParams?)` | Update the document. |
| `delete(queryParams?)` | Remove the document. |
**Usage examples:**
```js
const homepage = client.single('homepage');
// Fetch the default homepage content
const defaultHomepage = await homepage.find();
// Fetch the Spanish version of the homepage
const spanishHomepage = await homepage.find({ locale: 'es' });
// Update the homepage draft content
const updatedHomepage = await homepage.update(
{ title: 'Updated Homepage Title' },
{ status: 'draft' }
);
// Delete the homepage content
await homepage.delete();
```
### Working with files
The Strapi Client provides access to the [Media Library](/cms/features/media-library) via the `files` property. This allows you to retrieve and manage file metadata without directly interacting with the REST API.
The following methods are available for working with files. Click on the method name in the table to jump to the corresponding section with more details and examples:
| Method | Description |
|--------|-------------|
| [`find(params?)`](#find) | Retrieves a list of file metadata based on optional query parameters |
| [`findOne(fileId)`](#findone) | Retrieves the metadata for a single file by its ID |
| [`update(fileId, fileInfo)`](#update) | Updates metadata for an existing file |
| [`upload(file, options)`](#upload) | Uploads a file (Blob or Buffer) with an optional `options` object for metadata |
| [`delete(fileId)`](#delete) | Deletes a file by its ID |
#### `find`
The `strapi.client.files.find()` method retrieves a list of file metadata based on optional query parameters.
The method can be used as follows:
```js
// Initialize the client
const client = strapi({
baseURL: 'http://localhost:1337/api',
auth: 'your-api-token',
});
// Find all file metadata
const allFiles = await client.files.find();
console.log(allFiles);
// Find file metadata with filtering and sorting
const imageFiles = await client.files.find({
filters: {
mime: { $contains: 'image' }, // Only get image files
name: { $contains: 'avatar' }, // Only get files with 'avatar' in the name
},
sort: ['name:asc'], // Sort by name in ascending order
});
```
#### `findOne` {#findone}
The `strapi.client.files.findOne()` method retrieves the metadata for a single file by its id.
The method can be used as follows:
```js
// Initialize the client
const client = strapi({
baseURL: 'http://localhost:1337/api',
auth: 'your-api-token',
});
// Find file metadata by ID
const file = await client.files.findOne(1);
console.log(file.name);
console.log(file.url);
console.log(file.mime); // The file MIME type
```
#### `update`
The `strapi.client.files.update()` method updates metadata for an existing file, accepting 2 parameters, the `fileId`, and an object containing options such as the name, alternative text, and caption for the media.
The methods can be used as follows:
```js
// Initialize the client
const client = strapi({
baseURL: 'http://localhost:1337/api',
auth: 'your-api-token',
});
// Update file metadata
const updatedFile = await client.files.update(1, {
name: 'New file name',
alternativeText: 'Descriptive alt text for accessibility',
caption: 'A caption for the file',
});
```
#### `upload`
##### Response Structure
The `strapi.client.files.upload()` method returns an array of file objects, each with fields such as:
```json
{
"id": 1,
"name": "image.png",
"alternativeText": "Uploaded from Node.js Buffer",
"caption": "Example upload",
"mime": "image/png",
"url": "/uploads/image.png",
"size": 12345,
"createdAt": "2025-07-23T12:34:56.789Z",
"updatedAt": "2025-07-23T12:34:56.789Z"
}
```
:::note Additional response fields
The upload response includes additional fields beyond those shown above. See the complete FileResponse interface in the for all available fields.
:::
#### `delete`
The `strapi.client.files.delete()` method deletes a file by its ID.
The method can be used as follows:
```js
// Initialize the client
const client = strapi({
baseURL: 'http://localhost:1337/api',
auth: 'your-api-token',
});
// Delete a file by ID
const deletedFile = await client.files.delete(1);
console.log('File deleted successfully');
console.log('Deleted file ID:', deletedFile.id);
console.log('Deleted file name:', deletedFile.name);
```
## Handling Common Errors
The following errors might occur when sending queries through the Strapi Client:
| Error | Description |
|-------|-------------|
| Permission Errors | If the authenticated user does not have permission to upload or manage files, a `FileForbiddenError` is thrown. |
| HTTP Errors|If the server is unreachable, authentication fails, or there are network issues, an `HTTPError` is thrown. |
| Missing Parameters|When uploading a `Buffer`, both `filename` and `mimetype` must be provided in the options object. If either is missing, an error is thrown. |
:::strapi Additional information
More details about the Strapi Client may be found in the .
:::
# Content API
Source: https://docs.strapi.io/cms/api/content-api
# コンテンツにアクセスする Strapi API
Strapi プロジェクトを作成・設定し、[コンテンツタイプビルダー](/cms/features/content-type-builder) で構造を作り、[コンテンツマネージャー](/cms/features/content-manager) からデータを追加したら、次はそのコンテンツにアクセスする段階です。
フロントエンドアプリからは、Strapi の Content API を通じてコンテンツへアクセスできます。公開される経路は次のとおりです。
- 既定では [REST API](/cms/api/rest)
- [GraphQL プラグイン](/cms/plugins/graphql) をインストールしていれば [GraphQL API](/cms/api/graphql) も利用可能
REST API とやり取りするには、[Strapi Client](/cms/api/client) ライブラリも利用できます。
REST と GraphQL は、外部アプリに公開される Content API の上位レイヤーです。Strapi には、さらに 2 つの下位 API があります。
- [Document Service API](/cms/api/document-service) は `strapi.documents` から利用でき、[バックエンドサーバー](/cms/customization) や [プラグイン](/cms/plugins-development/developing-plugins) でデータベース操作するときの推奨 API です。Document Service は **document**
# Documents
Source: https://docs.strapi.io/cms/api/document
# Documents
Strapi 5 における **document** は API 上の概念です。document は、あるコンテンツタイプの 1 エントリーに対する複数のバリエーションをまとめたものです。
シングルタイプは 1 つの固有 document を持ち、コレクションタイプは複数の document を持てます。
管理パネル利用時は document という言葉は通常意識しません。ユーザーは [コンテンツマネージャー](/cms/features/content-manager) で **entry** を作成・編集します。例えば、特定ロケールの entry 一覧を見たり、特定ロケールの下書きを編集したりします。
ただし API レベルでは、entry のフィールド値は次のように複数状態を持ちます。
- 英語ロケールとフランス語ロケールで内容が異なる
- 各ロケールで draft 版と published 版が異なる
すべてのロケールにおける draft / published の内容をまとめる単位が document です。
[Document Service API](/cms/api/document-service) で document を操作すると、document 全体、またはその一部データを作成・取得・更新・削除できます。
次の図は、[国際化(i18n)](/cms/features/internationalization) や [Draft & Publish](/cms/features/draft-and-publish) の有効化状態ごとに、コンテンツがどのようなバリエーションを持つかを示します。
- コンテンツタイプで i18n が有効な場合、document は複数の **document locale** を持てます。
- コンテンツタイプで Draft & Publish が有効な場合、document は **published** と **draft** の 2 バージョンを持てます。
:::strapi document データを扱う API
document またはその中のデータを扱うには次を使います。
- バックエンドサーバー側(コントローラー、サービス、プラグインのバックエンド側など)では [Document Service API](/cms/api/document-service) を使う。
- アプリのフロント側では [REST API](/cms/api/rest) または [GraphQL API](/cms/api/graphql) でデータを取得する。
API 全体の説明は [Content API の導入](/cms/api/content-api) を参照してください。
:::
:::info 既定で返るバージョン
バックエンド API とフロント API では、パラメーター未指定時の既定バージョンが異なります。
- Document Service API は既定で draft を返す
- REST / GraphQL API は既定で published を返す
:::
# Document Service API
Source: https://docs.strapi.io/cms/api/document-service
# Document Service API
The Document Service API is built on top of the **Query Engine API** and is used to perform CRUD ([create](#create), [retrieve](#findone), [update](#update), and [delete](#delete)) operations on **documents**
:::strapi Entity Service API is deprecated in Strapi 5
The Document Service API replaces the Entity Service API used in Strapi v4 (
The `findOne()` method returns the matching document if found, otherwise returns `null`.
### `findFirst()`
Find the first document matching the parameters.
Syntax: `findFirst(parameters: Params) => Document`
#### Parameters
| Parameter | Description | Default | Type |
|-----------|-------------|---------|------|
| [`locale`](/cms/api/document-service/locale#find-first) | Locale of the documents to find. | Default locale | String or `undefined` |
| [`status`](/cms/api/document-service/status#find-first) | _If [Draft & Publish](/cms/features/draft-and-publish) is enabled for the content-type_: Publication status, can be:
`'published'` to find only published documents
`'draft'` to find only draft documents
| `'draft'` | `'published'` or `'draft'` |
| [`filters`](/cms/api/document-service/filters) | [Filters](/cms/api/document-service/filters) to use | `null` | Object |
| [`fields`](/cms/api/document-service/fields#findfirst) | [Select fields](/cms/api/document-service/fields#findfirst) to return | All fields (except those not populate by default) | Object |
| [`populate`](/cms/api/document-service/populate) | [Populate](/cms/api/document-service/populate) results with additional fields. | `null` | Object |
#### Examples
##### Generic example
By default, `findFirst()` returns the draft version, in the default locale, of the first document for the passed unique identifier (collection type id or single type id):
##### Find the first document matching parameters
Pass some parameters to `findFirst()` to return the first document matching them.
If no `locale` or `status` parameters are passed, results return the draft version for the default locale:
### `findMany()`
Find documents matching the parameters.
Syntax: `findMany(parameters: Params) => Document[]`
#### Parameters
| Parameter | Description | Default | Type |
|-----------|-------------|---------|------|
| [`locale`](/cms/api/document-service/locale#find-many) | Locale of the documents to find. | Default locale | String or `undefined` |
| [`status`](/cms/api/document-service/status#find-many) | _If [Draft & Publish](/cms/features/draft-and-publish) is enabled for the content-type_: Publication status, can be:
`'published'` to find only published documents
`'draft'` to find only draft documents
| `'draft'` | `'published'` or `'draft'` |
| [`filters`](/cms/api/document-service/filters) | [Filters](/cms/api/document-service/filters) to use | `null` | Object |
| [`fields`](/cms/api/document-service/fields#findmany) | [Select fields](/cms/api/document-service/fields#findmany) to return | All fields (except those not populate by default) | Object |
| [`populate`](/cms/api/document-service/populate) | [Populate](/cms/api/document-service/populate) results with additional fields. | `null` | Object |
| [`pagination`](/cms/api/document-service/sort-pagination#pagination) | [Paginate](/cms/api/document-service/sort-pagination#pagination) results |
| [`sort`](/cms/api/document-service/sort-pagination#sort) | [Sort](/cms/api/document-service/sort-pagination#sort) results | | |
#### Examples
##### Generic example
When no parameter is passed, `findMany()` returns the draft version in the default locale for each document:
##### Find documents matching parameters
Available filters are detailed in the [filters](/cms/api/document-service/filters) page of the Document Service API reference.
If no `locale` or `status` parameters are passed, results return the draft version for the default locale:
### `create()`
Creates a drafted document and returns it.
Pass fields for the content to create in a `data` object.
Syntax: `create(parameters: Params) => Document`
#### Parameters
| Parameter | Description | Default | Type |
|-----------|-------------|---------|------|
| [`locale`](/cms/api/document-service/locale#create) | Locale of the documents to create. | Default locale | String or `undefined` |
| [`fields`](/cms/api/document-service/fields#create) | [Select fields](/cms/api/document-service/fields#create) to return | All fields (except those not populated by default) | Object |
| [`status`](/cms/api/document-service/status#create) | _If [Draft & Publish](/cms/features/draft-and-publish) is enabled for the content-type_: Can be set to `'published'` to automatically publish the draft version of a document while creating it | -| `'published'` |
| [`populate`](/cms/api/document-service/populate) | [Populate](/cms/api/document-service/populate) results with additional fields. | `null` | Object |
#### Example
If no `locale` parameter is passed, `create()` creates the draft version of the document for the default locale:
:::tip
If the [Draft & Publish](/cms/features/draft-and-publish) feature is enabled on the content-type, you can automatically publish a document while creating it (see [`status` documentation](/cms/api/document-service/status#create)).
:::
### `update()`
Updates document versions and returns them.
Syntax: `update(parameters: Params) => Promise
### `delete()`
Deletes one document, or a specific locale of it.
Syntax: `delete(parameters: Params): Promise<{ documentId: ID, entries: Number }>`
#### Parameters
| Parameter | Description | Default | Type |
|-----------|-------------|---------|------|
| `documentId`| Document id | | `ID`|
| [`locale`](/cms/api/document-service/locale#delete) | Locale version of the document to delete. | `null` (deletes only the default locale) | String, `'*'`, or `null` |
| [`filters`](/cms/api/document-service/filters) | [Filters](/cms/api/document-service/filters) to use | `null` | Object |
| [`fields`](/cms/api/document-service/fields#delete) | [Select fields](/cms/api/document-service/fields#delete) to return | All fields (except those not populate by default) | Object |
| [`populate`](/cms/api/document-service/populate) | [Populate](/cms/api/document-service/populate) results with additional fields. | `null` | Object |
#### Example
If no `locale` parameter is passed, `delete()` only deletes the default locale version of a document. This deletes both the draft and published versions:
### `publish()`
Publishes one or multiple locales of a document.
This method is only available if [Draft & Publish](/cms/features/draft-and-publish) is enabled on the content-type.
Syntax: `publish(parameters: Params): Promise<{ documentId: ID, entries: Number }>`
#### Parameters
| Parameter | Description | Default | Type |
|-----------|-------------|---------|------|
| `documentId`| Document id | | `ID`|
| [`locale`](/cms/api/document-service/locale#publish) | Locale of the documents to publish. | Only the default locale | String, `'*'`, or `null` |
| [`filters`](/cms/api/document-service/filters) | [Filters](/cms/api/document-service/filters) to use | `null` | Object |
| [`fields`](/cms/api/document-service/fields#publish) | [Select fields](/cms/api/document-service/fields#publish) to return | All fields (except those not populate by default) | Object |
| [`populate`](/cms/api/document-service/populate) | [Populate](/cms/api/document-service/populate) results with additional fields. | `null` | Object |
#### Example
If no `locale` parameter is passed, `publish()` only publishes the default locale version of the document:
### `unpublish()`
Unpublishes one or all locale versions of a document, and returns how many locale versions were unpublished.
This method is only available if [Draft & Publish](/cms/features/draft-and-publish) is enabled on the content-type.
Syntax: `unpublish(parameters: Params): Promise<{ documentId: ID, entries: Number }>`
#### Parameters
| Parameter | Description | Default | Type |
|-----------|-------------|---------|------|
| `documentId`| Document id | | `ID`|
| [`locale`](/cms/api/document-service/locale#unpublish) | Locale of the documents to unpublish. | Only the default locale | String, `'*'`, or `null` |
| [`filters`](/cms/api/document-service/filters) | [Filters](/cms/api/document-service/filters) to use | `null` | Object |
| [`fields`](/cms/api/document-service/fields#unpublish) | [Select fields](/cms/api/document-service/fields#unpublish) to return | All fields (except those not populate by default) | Object |
| [`populate`](/cms/api/document-service/populate) | [Populate](/cms/api/document-service/populate) results with additional fields. | `null` | Object |
#### Example
If no `locale` parameter is passed, `unpublish()` only unpublishes the default locale version of the document:
### `discardDraft()`
Discards draft data and overrides it with the published version.
This method is only available if [Draft & Publish](/cms/features/draft-and-publish) is enabled on the content-type.
Syntax: `discardDraft(parameters: Params): Promise<{ documentId: ID, entries: Number }>`
#### Parameters
| Parameter | Description | Default | Type |
|-----------|-------------|---------|------|
| `documentId`| Document id | | `ID`|
| [`locale`](/cms/api/document-service/locale#discard-draft) | Locale of the documents to discard. | Only the default locale. | String, `'*'`, or `null` |
| [`filters`](/cms/api/document-service/filters) | [Filters](/cms/api/document-service/filters) to use | `null` | Object |
| [`fields`](/cms/api/document-service/fields#discarddraft) | [Select fields](/cms/api/document-service/fields#discarddraft) to return | All fields (except those not populate by default) | Object |
| [`populate`](/cms/api/document-service/populate) | [Populate](/cms/api/document-service/populate) results with additional fields. | `null` | Object |
#### Example
If no `locale` parameter is passed, `discardDraft()` discards draft data and overrides it with the published version only for the default locale:
### `count()`
Count the number of documents that match the provided parameters.
Syntax: `count(parameters: Params) => number`
#### Parameters
| Parameter | Description | Default | Type |
|-----------|-------------|---------|------|
| [`locale`](/cms/api/document-service/locale#count) | Locale of the documents to count | Default locale | String or `null` |
| [`status`](/cms/api/document-service/status#count) | _If [Draft & Publish](/cms/features/draft-and-publish) is enabled for the content-type_: Publication status, can be:
`'published'` to find only published documents
`'draft'` to find draft documents (will return all documents)
| `'draft'` | `'published'` or `'draft'` |
| [`filters`](/cms/api/document-service/filters) | [Filters](/cms/api/document-service/filters) to use | `null` | Object |
:::note
Since published documents necessarily also have a draft counterpart, a published document is still counted as having a draft version.
This means that counting with the `status: 'draft'` parameter still returns the total number of documents matching other parameters, even if some documents have already been published and are not displayed as "draft" or "modified" in the Content Manager anymore. There currently is no way to prevent already published documents from being counted.
:::
#### Examples
##### Generic example
If no parameter is passed, the `count()` method the total number of documents for the default locale:
##### Count published documents
To count only published documents, pass `status: 'published'` along with other parameters to the `count()` method.
If no `locale` parameter is passed, documents are counted for the default locale.
##### Count documents with filters
Any [filters](/cms/api/document-service/filters) can be passed to the `count()` method.
If no `locale` and no `status` parameter is passed, draft documents (which is the total of available documents for the locale since even published documents are counted as having a draft version) are counted only for the default locale:
```js
/**
* Count number of draft documents (default if status is omitted)
* in English (default locale)
* whose name starts with 'Pizzeria'
*/
strapi.documents('api::restaurant.restaurant').count({ filters: { name: { $startsWith: "Pizzeria" }}})`
```
# Using fields with the Document Service API
Source: https://docs.strapi.io/cms/api/document-service/fields
# Document Service API: Selecting fields
By default the [Document Service API](/cms/api/document-service) returns all the fields of a document but does not populate any fields. This page describes how to use the `fields` parameter to return only specific fields with the query results.
:::tip
You can also use the `populate` parameter to populate relations, media fields, components, or dynamic zones (see the [`populate` parameter](/cms/api/document-service/populate) documentation).
:::
## Select fields with `findFirst()` queries {#findfirst}
To select fields to return while [finding the first document](/cms/api/document-service#findfirst) matching the parameters with the Document Service API:
## Select fields with `findMany()` queries {#findmany}
To select fields to return while [finding documents](/cms/api/document-service#findmany) with the Document Service API:
## Select fields with `create()` queries {#create}
To select fields to return while [creating documents](/cms/api/document-service#create) with the Document Service API:
## Select fields with `update()` queries {#update}
To select fields to return while [updating documents](/cms/api/document-service#update) with the Document Service API:
## Select fields with `delete()` queries {#delete}
To select fields to return while [deleting documents](/cms/api/document-service#delete) with the Document Service API:
## Select fields with `publish()` queries {#publish}
To select fields to return while [publishing documents](/cms/api/document-service#publish) with the Document Service API:
## Select fields with `unpublish()` queries {#unpublish}
To select fields to return while [unpublishing documents](/cms/api/document-service#unpublish) with the Document Service API:
## Select fields with `discardDraft()` queries {#discarddraft}
To select fields to return while [discarding draft versions of documents](/cms/api/document-service#discarddraft) with the Document Service API:
# Using filters with the Document Service API
Source: https://docs.strapi.io/cms/api/document-service/filters
# Document Service API: Filters
The [Document Service API](/cms/api/document-service) offers the ability to filter results.
The following operators are available:
| Operator | Description |
| -------------------------------- | ---------------------------------------- |
| [`$eq`](#eq) | Equal |
| [`$eqi`](#eqi) | Equal (case-insensitive) |
| [`$ne`](#ne) | Not equal |
| [`$nei`](#nei) | Not equal (case-insensitive) |
| [`$lt`](#lt) | Less than |
| [`$lte`](#lte) | Less than or equal to |
| [`$gt`](#gt) | Greater than |
| [`$gte`](#gte) | Greater than or equal to |
| [`$in`](#in) | Included in an array |
| [`$notIn`](#notin) | Not included in an array |
| [`$contains`](#contains) | Contains |
| [`$notContains`](#notcontains) | Does not contain |
| [`$containsi`](#containsi) | Contains (case-insensitive) |
| [`$notContainsi`](#notcontainsi) | Does not contain (case-insensitive) |
| [`$null`](#null) | Is null |
| [`$notNull`](#notnull) | Is not null |
| [`$between`](#between) | Is between |
| [`$startsWith`](#startswith) | Starts with |
| [`$startsWithi`](#startswithi) | Starts with (case-insensitive) |
| [`$endsWith`](#endswith) | Ends with |
| [`$endsWithi`](#endswithi) | Ends with (case-insensitive) |
| [`$or`](#or) | Joins the filters in an "or" expression |
| [`$and`](#and) | Joins the filters in an "and" expression |
| [`$not`](#not) | Joins the filters in an "not" expression |
## Attribute operators
### `$not`
Negates the nested condition(s).
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
title: {
$not: {
$contains: 'Hello World',
},
},
},
});
```
### `$eq`
Attribute equals input value.
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
title: {
$eq: 'Hello World',
},
},
});
```
`$eq` can be omitted:
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
title: 'Hello World',
},
});
```
### `$eqi`
Attribute equals input value (case-insensitive).
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
title: {
$eqi: 'HELLO World',
},
},
});
```
### `$ne`
Attribute does not equal input value.
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
title: {
$ne: 'ABCD',
},
},
});
```
### `$nei`
Attribute does not equal input value (case-insensitive).
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
title: {
$nei: 'abcd',
},
},
});
```
### `$in`
Attribute is contained in the input list.
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
title: {
$in: ['Hello', 'Hola', 'Bonjour'],
},
},
});
```
`$in` can be omitted when passing an array of values:
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
title: ['Hello', 'Hola', 'Bonjour'],
},
});
```
### `$notIn`
Attribute is not contained in the input list.
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
title: {
$notIn: ['Hello', 'Hola', 'Bonjour'],
},
},
});
```
### `$lt`
Attribute is less than the input value.
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
rating: {
$lt: 10,
},
},
});
```
### `$lte`
Attribute is less than or equal to the input value.
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
rating: {
$lte: 10,
},
},
});
```
### `$gt`
Attribute is greater than the input value.
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
rating: {
$gt: 5,
},
},
});
```
### `$gte`
Attribute is greater than or equal to the input value.
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
rating: {
$gte: 5,
},
},
});
```
### `$between`
Attribute is between the 2 input values, boundaries included (e.g., `$between[1, 3]` will also return `1` and `3`).
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
rating: {
$between: [1, 20],
},
},
});
```
### `$contains`
Attribute contains the input value (case-sensitive).
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
title: {
$contains: 'Hello',
},
},
});
```
### `$notContains`
Attribute does not contain the input value (case-sensitive).
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
title: {
$notContains: 'Hello',
},
},
});
```
### `$containsi`
Attribute contains the input value. `$containsi` is not case-sensitive, while [$contains](#contains) is.
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
title: {
$containsi: 'hello',
},
},
});
```
### `$notContainsi`
Attribute does not contain the input value. `$notContainsi` is not case-sensitive, while [$notContains](#notcontains) is.
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
title: {
$notContainsi: 'hello',
},
},
});
```
### `$startsWith`
Attribute starts with input value (case-sensitive).
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
title: {
$startsWith: 'ABCD',
},
},
});
```
### `$startsWithi`
Attribute starts with input value (case-insensitive).
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
title: {
$startsWithi: 'ABCD', // will return the same as filtering with 'abcd'
},
},
});
```
### `$endsWith`
Attribute ends with input value (case-sensitive).
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
title: {
$endsWith: 'ABCD',
},
},
});
```
### `$endsWithi`
Attribute ends with input value (case-insensitive).
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
title: {
$endsWith: 'ABCD', // will return the same as filtering with 'abcd'
},
},
},
});
```
### `$null`
Attribute is `null`.
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
title: {
$null: true,
},
},
});
```
### `$notNull`
Attribute is not `null`.
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
title: {
$notNull: true,
},
},
});
```
## Logical operators
### `$and`
All nested conditions must be `true`.
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
$and: [
{
title: 'Hello World',
},
{
createdAt: { $gt: '2021-11-17T14:28:25.843Z' },
},
],
},
});
```
`$and` will be used implicitly when passing an object with nested conditions:
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
title: 'Hello World',
createdAt: { $gt: '2021-11-17T14:28:25.843Z' },
},
});
```
### `$or`
One or many nested conditions must be `true`.
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
$or: [
{
title: 'Hello World',
},
{
createdAt: { $gt: '2021-11-17T14:28:25.843Z' },
},
],
},
});
```
### `$not`
Negates the nested conditions.
**Example**
```js
const entries = await strapi.documents('api::article.article').findMany({
filters: {
$not: {
title: 'Hello World',
},
},
});
```
:::note
`$not` can be used as:
- a logical operator (e.g. in `filters: { $not: { // conditions… }}`)
- [an attribute operator](#not) (e.g. in `filters: { attribute-name: $not: { … } }`).
:::
:::tip
`$and`, `$or` and `$not` operators are nestable inside of another `$and`, `$or` or `$not` operator.
:::
# Using the locale parameter with the Document Service API
Source: https://docs.strapi.io/cms/api/document-service/locale
# Document Service API: Using the `locale` parameter
By default the [Document Service API](/cms/api/document-service) returns the default locale version of documents (which is 'en', i.e. the English version, unless another default locale has been set for the application, see [Internationalization (i18n) feature](/cms/features/internationalization)). This page describes how to use the `locale` parameter to get or manipulate data only for specific locales.
## Get a locale version with `findOne()` {#find-one}
If a `locale` is passed, the [`findOne()` method](/cms/api/document-service#findone) of the Document Service API returns the version of the document for this locale:
If no `status` parameter is passed, the `draft` version is returned by default.
## Get a locale version with `findFirst()` {#find-first}
To return a specific locale while [finding the first document](/cms/api/document-service#findfirst) matching the parameters with the Document Service API:
If no `status` parameter is passed, the `draft` version is returned by default.
## Get locale versions with `findMany()` {#find-many}
When a `locale` is passed to the [`findMany()` method](/cms/api/document-service#findmany) of the Document Service API, the response will return all documents that have this locale available.
If no `status` parameter is passed, the `draft` versions are returned by default.
Explanation:
Given the following 4 documents that have various locales:
- Document A:
- en
- `fr`
- it
- Document B:
- en
- it
- Document C:
- `fr`
- Document D:
- `fr`
- it
`findMany({ locale: 'fr' })` would only return the draft version of the documents that have a `‘fr’` locale version, that is documents A, C, and D.
## `create()` a document for a locale {#create}
To create a document for specific locale, pass the `locale` as a parameter to the [`create` method](/cms/api/document-service#create) of the Document Service API:
## `update()` a locale version {#update}
To update only a specific locale version of a document, pass the `locale` parameter to the [`update()` method](/cms/api/document-service#update) of the Document Service API:
## `delete()` locale versions {#delete}
Use the `locale` parameter with the [`delete()` method](/cms/api/document-service#delete) of the Document Service API to delete only some locales. Unless a specific `status` parameter is passed, this deletes both the draft and published versions.
### Delete a locale version
To delete a specific locale version of a document:
### Delete all locale versions
The `*` wildcard is supported by the `locale` parameter and can be used to delete all locale versions of a document:
## `publish()` locale versions {#publish}
To publish only specific locale versions of a document with the [`publish()` method](/cms/api/document-service#publish) of the Document Service API, pass `locale` as a parameter:
### Publish a locale version
To publish a specific locale version of a document:
### Publish all locale versions
The `*` wildcard is supported by the `locale` parameter to publish all locale versions of a document:
## `unpublish()` locale versions {#unpublish}
To publish only specific locale versions of a document with the [`unpublish()` method](/cms/api/document-service#unpublish) of the Document Service API, pass `locale` as a parameter:
### Unpublish a locale version
To unpublish a specific locale version of a document, pass the `locale` as a parameter to `unpublish()`:
### Unpublish all locale versions
The `*` wildcard is supported by the `locale` parameter, to unpublish all locale versions of a document:
## `discardDraft()` for locale versions {#discard-draft}
To discard draft data only for some locales versions of a document with the [`discardDraft()` method](/cms/api/document-service#discarddraft) of the Document Service API, pass `locale` as a parameter:
### Discard draft for a locale version
To discard draft data for a specific locale version of a document and override it with data from the published version for this locale, pass the `locale` as a parameter to `discardDraft()`:
### Discard drafts for all locale versions
The `*` wildcard is supported by the `locale` parameter, to discard draft data for all locale versions of a document and replace them with the data from the published versions:
## `count()` documents for a locale {#count}
To count documents for a specific locale, pass the `locale` along with other parameters to the [`count()` method](/cms/api/document-service#count) of the Document Service API.
If no `status` parameter is passed, draft documents are counted (which is the total of available documents for the locale since even published documents are counted as having a draft version):
```js
// Count number of published documents in French
strapi.documents('api::restaurant.restaurant').count({ locale: 'fr' });
```
# Extending the Document Service behavior
Source: https://docs.strapi.io/cms/api/document-service/middlewares
# Document Service API: Middlewares
The [Document Service API](/cms/api/document-service) offers the ability to extend its behavior thanks to middlewares.
Document Service middlewares allow you to perform actions before and/or after a method runs.
The diagram represents a simplified version of how a request travels through the Strapi back end, with the Document Service highlighted. The backend customization introduction page includes a complete, interactive diagram.
## Registering a middleware
Syntax: `strapi.documents.use(middleware)`
### Parameters
A middleware is a function that receives a context and a next function.
Syntax: `(context, next) => ReturnType`
| Parameter | Description | Type |
|-----------|---------------------------------------|------------|
| `context` | Middleware context | `Context` |
| `next` | Call the next middleware in the stack | `function` |
#### `context`
| Parameter | Description | Type |
|---------------|--------------------------------------------------------------------------------------|---------------|
| `action` | The method that is running ([see available methods](/cms/api/document-service)) | `string` |
| `params` | The method params ([see available methods](/cms/api/document-service)) | `Object` |
| `uid` | Content type unique identifier | `string` |
| `contentType` | Content type | `ContentType` |
Examples:
The following examples show what `context` might include depending on the method called:
#### `next`
`next` is a function without parameters that calls the next middleware in the stack and return its response.
**Example**
```js
strapi.documents.use((context, next) => {
return next();
});
```
### Where to register
Generaly speaking you should register your middlewares during the Strapi registration phase.
#### Users
The middleware must be registered in the general `register()` lifecycle method:
```js title="/src/index.js|ts"
module.exports = {
register({ strapi }) {
strapi.documents.use((context, next) => {
// your logic
return next();
});
},
// bootstrap({ strapi }) {},
// destroy({ strapi }) {},
};
```
#### Plugin developers
The middleware must be registered in the plugin's `register()` lifecycle method:
```js title="/(plugin-root-folder)/strapi-server.js|ts"
module.exports = {
register({ strapi }) {
strapi.documents.use((context, next) => {
// your logic
return next();
});
},
// bootstrap({ strapi }) {},
// destroy({ strapi }) {},
};
```
## Implementing a middleware
When implementing a middleware, always return the response from `next()`.
Failing to do this will break the Strapi application.
### Examples
```js
const applyTo = ['api::article.article'];
strapi.documents.use((context, next) => {
// Only run for certain content types
if (!applyTo.includes(context.uid)) {
return next();
}
// Only run for certain actions
if (['create', 'update'].includes(context.action)) {
context.params.data.fullName = `${context.params.data.firstName} ${context.params.data.lastName}`;
}
const result = await next();
// do something with the result before returning it
return result
});
```
:::strapi Lifecycle hooks
The Document Service API triggers various database lifecycle hooks based on which method is called. For a complete reference, see [Document Service API: Lifecycle hooks](/cms/migration/v4-to-v5/breaking-changes/lifecycle-hooks-document-service#table).
:::
# Using Populate with the Document Service API
Source: https://docs.strapi.io/cms/api/document-service/populate
# Document Service API: Populating fields
By default the [Document Service API](/cms/api/document-service) does not populate any relations, media fields, components, or dynamic zones. This page describes how to use the `populate` parameter to populate specific fields.
:::tip
You can also use the `select` parameter to return only specific fields with the query results (see the [`select` parameter](/cms/api/document-service/fields) documentation).
:::
:::caution
If the Users & Permissions plugin is installed, the `find` permission must be enabled for the content-types that are being populated. If a role doesn't have access to a content-type it will not be populated.
:::
## Relations and media fields
Queries can accept a `populate` parameter to explicitly define which fields to populate, with the following syntax option examples.
### Populate 1 level for all relations
To populate one-level deep for all relations, use the `*` wildcard in combination with the `populate` parameter:
### Populate 1 level for specific relations
To populate specific relations one-level deep, pass the relation names in a `populate` array:
### Populate several levels deep for specific relations
To populate specific relations several levels deep, use the object format with `populate`:
## Components & Dynamic Zones
Components are populated the same way as relations:
Dynamic zones are highly dynamic content structures by essence. To populate a dynamic zone, you must define per-component populate queries using the `on` property.
## Populating with `create()`
To populate while creating documents:
## Populating with `update()`
To populate while updating documents:
## Populating with `publish()`
To populate while publishing documents (same behavior with `unpublish()` and `discardDraft()`):
# Using Sort & Pagination with the Document Service API
Source: https://docs.strapi.io/cms/api/document-service/sort-pagination
# Document Service API: Sorting and paginating results
The [Document Service API](/cms/api/document-service) offers the ability to sort and paginate query results.
## Sort
To sort results returned by the Document Service API, include the `sort` parameter with queries.
### Sort on a single field
To sort results based on a single field:
### Sort on multiple fields
To sort on multiple fields, pass them all in an array:
## Pagination
To paginate results, pass the `limit` and `start` parameters:
# Using Draft & Publish with the Document Service API
Source: https://docs.strapi.io/cms/api/document-service/status
# Document Service API: Usage with Draft & Publish
By default the [Document Service API](/cms/api/document-service) returns the draft version of a document when the [Draft & Publish](/cms/features/draft-and-publish) feature is enabled. This page describes how to use the `status` parameter to:
- return the published version of a document,
- count documents depending on their status,
- and directly publish a document while creating it or updating it.
:::note
Passing `{ status: 'draft' }` to a Document Service API query returns the same results as not passing any `status` parameter.
:::
## Get the published version with `findOne()` {#find-one}
`findOne()` queries return the draft version of a document by default.
To return the published version while [finding a specific document](/cms/api/document-service#findone) with the Document Service API, pass `status: 'published'`:
## Get the published version with `findFirst()` {#find-first}
`findFirst()` queries return the draft version of a document by default.
To return the published version while [finding the first document](/cms/api/document-service#findfirst) with the Document Service API, pass `status: 'published'`:
## Get the published version with `findMany()` {#find-many}
`findMany()` queries return the draft version of documents by default.
To return the published version while [finding documents](/cms/api/document-service#findmany) with the Document Service API, pass `status: 'published'`:
## `count()` only draft or published versions {#count}
To take into account only draft or published versions of documents while [counting documents](/cms/api/document-service#count) with the Document Service API, pass the corresponding `status` parameter:
```js
// Count draft documents (also actually includes published documents)
const draftsCount = await strapi.documents("api::restaurant.restaurant").count({
status: 'draft'
});
```
```js
// Count only published documents
const publishedCount = await strapi.documents("api::restaurant.restaurant").count({
status: 'published'
});
```
:::note
Since published documents necessarily also have a draft counterpart, a published document is still counted as having a draft version.
This means that counting with the `status: 'draft'` parameter still returns the total number of documents matching other parameters, even if some documents have already been published and are not displayed as "draft" or "modified" in the Content Manager anymore. There currently is no way to prevent already published documents from being counted.
:::
## Create a draft and publish it {#create}
To automatically publish a document while creating it, add `status: 'published'` to parameters passed to `create()`:
## Update a draft and publish it {#update}
To automatically publish a document while updating it, add `status: 'published'` to parameters passed to `update()`:
# GraphQL API
Source: https://docs.strapi.io/cms/api/graphql
# GraphQL API
The GraphQL API allows performing queries and mutations to interact with the [content-types](/cms/backend-customization/models#content-types) through Strapi's [GraphQL plugin](/cms/plugins/graphql). Results can be [filtered](#filters), [sorted](#sorting) and [paginated](#pagination).
:::prerequisites
To use the GraphQL API, install the [GraphQL](/cms/plugins/graphql) plugin:
:::
Once installed, the GraphQL playground is accessible at the `/graphql` URL and can be used to interactively build your queries and mutations and read documentation tailored to your content-types:
#### Fetch relations
You can ask to include relation data in your flat queries or in your
:::
### Fetch media fields
Media fields content is fetched just like other attributes.
The following example fetches the `url` attribute value for each `cover` media field attached to each document from the "Restaurants" content-type:
```graphql
{
restaurants {
images {
documentId
url
}
}
}
```
For multiple media fields, you can use flat queries or
### Fetch components
Components content is fetched just like other attributes.
The following example fetches the `label`, `start_date`, and `end_date` attributes values for each `closingPeriod` component added to each document from the "Restaurants" content-type:
```graphql
{
restaurants {
closingPeriod {
label
start_date
end_date
}
}
}
```
### Fetch dynamic zone data
Dynamic zones are union types in GraphQL so you need to use
```graphql title="Simple examples for membership operators (in, notIn)"
# in - returns restaurants with category either "pizza" or "burger"
{
restaurants(filters: { category: { in: ["pizza", "burger"] } }) {
name
}
}
# notIn - returns restaurants whose category is neither "pizza" nor "burger"
{
restaurants(filters: { category: { notIn: ["pizza", "burger"] } }) {
name
}
}
```
```graphql title="Simple examples for null checks operators (null, notNull)"
# null - returns restaurants where description is null
{
restaurants(filters: { description: { null: true } }) {
name
}
}
# notNull - returns restaurants where description is not null
{
restaurants(filters: { description: { notNull: true } }) {
name
}
}
```
```graphql title="Simple examples for logical operators (and, or, not)"
# and - both category must be "pizza" AND averagePrice must be < 20
{
restaurants(filters: {
and: [
{ category: { eq: "pizza" } },
{ averagePrice: { lt: 20 } }
]
}) {
name
}
}
# or - category is "pizza" OR category is "burger"
{
restaurants(filters: {
or: [
{ category: { eq: "pizza" } },
{ category: { eq: "burger" } }
]
}) {
name
}
}
# not - category must NOT be "pizza"
{
restaurants(filters: {
not: { category: { eq: "pizza" } }
}) {
name
}
}
```
```graphql title="Example with nested logical operators: use and, or, and not to find pizzerias under 20 euros"
{
restaurants(
filters: {
and: [
{ not: { averagePrice: { gte: 20 } } }
{
or: [
{ name: { eq: "Pizzeria" } }
{ name: { startsWith: "Pizzeria" } }
]
}
]
}
) {
documentId
name
averagePrice
}
}
```
### Fetch a document in a specific locale {#locale-fetch}
To fetch a documents
### Create a new localized document {#locale-create}
The `locale` field can be passed to create a localized document
# OpenAPI specification
Source: https://docs.strapi.io/cms/api/openapi
# OpenAPI specification generation
Strapi provides a command-line tool to generate
You can also path an optional `--output` argument to specify the path and filename, as in the following example:
### Specification structure and content
The generated OpenAPI specification follows the
The generated OpenAPI specification includes all available API endpoints in your Strapi application, and information about these endpoints, such as the following:
- CRUD operations for all content types
- Custom API routes defined in your application
- Authentication endpoints for user management
- File upload endpoints for media handling
- Plugin endpoints from installed plugins
## Integrating with Swagger UI
With the following steps you can quickly generate a [Swagger UI](https://swagger.io/)-compatible page:
1. Generate a specification:
2. Update [the `/config/middlewares.js` configuration file](/cms/configurations/middlewares) with the following code:
This will ensure the Swagger UI display from is not blocked by Strapi's CSP policy handled by the [security middleware](/cms/configurations/middlewares#security).
3. Create a `public/openapi.html` file in your Strapi project to display the Swagger UI, with the following code:
```html
API Documentation
```
4. Restart the Strapi server with `yarn develop` or `npm run develop` and visit the `/openapi.html` page. The Swagger UI should be displayed:

# REST API reference
Source: https://docs.strapi.io/cms/api/rest
# REST API reference
The REST API allows accessing the [content-types](/cms/backend-customization/models) through API endpoints. Strapi automatically creates [API endpoints](#endpoints) when a content-type is created. [API parameters](/cms/api/rest/parameters) can be used when querying API endpoints to refine the results.
This section of the documentation is for the REST API reference for content-types. We also have [guides](/cms/api/rest/guides/intro) available for specific use cases.
:::prerequisites
All content types are private by default and need to be either made public or queries need to be authenticated with the proper permissions. See the [Quick Start Guide](/cms/quick-start#step-4-set-roles--permissions), the user guide for the [Users & Permissions feature](/cms/features/users-permissions#roles), and [API tokens configuration documentation](/cms/features/api-tokens) for more details.
:::
:::note
By default, the REST API responses only include top-level fields and does not populate any relations, media fields, components, or dynamic zones. Use the [`populate` parameter](/cms/api/rest/populate-select) to populate specific fields. Ensure that the find permission is given to the field(s) for the relation(s) you populate.
:::
:::strapi Strapi Client
The [Strapi Client](/cms/api/client) library simplifies interactions with your Strapi back end, providing a way to fetch, create, update, and delete content.
:::
## Endpoints
For each Content-Type, the following endpoints are automatically generated:
Plural API ID vs. Singular API ID:
In the following tables:
- `:singularApiId` refers to the value of the "API ID (Singular)" field of the content-type,
- and `:pluralApiId` refers to the value of the "API ID (Plural)" field of the content-type.
These values are defined when creating a content-type in the Content-Type Builder, and can be found while editing a content-type in the admin panel (see [User Guide](/cms/features/content-type-builder#creating-content-types)). For instance, by default, for an "Article" content-type:
- `:singularApiId` will be `article`
- `:pluralApiId` will be `articles`
Real-world examples of endpoints:
The following endpoint examples are taken from the
:::strapi Upload API
The Upload package (which powers the [Media Library feature](/cms/features/media-library)) has a specific API accessible through its [`/api/upload` endpoints](/cms/api/rest/upload).
:::
:::note
[Components](/cms/backend-customization/models#components-json) don't have API endpoints.
:::
## Requests
:::strapi Strapi 5 vs. Strapi v4
Strapi 5's Content API includes 2 major differences with Strapi v4:
- The response format has been flattened, which means attributes are no longer nested in a `data.attributes` object and are directly accessible at the first level of the `data` object (e.g., a content-type's "title" attribute is accessed with `data.title`).
- Strapi 5 now uses **documents**
### Get a document {#get}
Returns a document by `documentId`.
:::strapi Strapi 5 vs. Strapi v4
In Strapi 5, a specific document is reached by its `documentId`.
:::
### Create a document {#create}
Creates a document and returns its value.
If the [Internationalization (i18n) plugin](/cms/features/internationalization) is installed, it's possible to use POST requests to the REST API to [create localized documents](/cms/api/rest/locale#rest-delete).
:::note
While creating a document, you can define its relations and their order (see [Managing relations through the REST API](/cms/api/rest/relations.md) for more details).
:::
### Update a document {#update}
Partially updates a document by `id` and returns its value.
Send a `null` value to clear fields.
:::note NOTES
* Even with the [Internationalization (i18n) plugin](/cms/features/internationalization) installed, it's currently not possible to [update the locale of a document](/cms/api/rest/locale#rest-update).
* While updating a document, you can define its relations and their order (see [Managing relations through the REST API](/cms/api/rest/relations) for more details).
:::
### Delete a document {#delete}
Deletes a document.
`DELETE` requests only send a 204 HTTP status code on success and do not return any data in the response body.
# Filters
Source: https://docs.strapi.io/cms/api/rest/filters
# REST API: Filters
The [REST API](/cms/api/rest) offers the ability to filter results found with its ["Get entries"](/cms/api/rest#get-all) method.
Using optional Strapi features can provide some more filters:
- If the [Internationalization (i18n) plugin](/cms/features/internationalization) is enabled on a content-type, it's possible to filter by locale.
- If the [Draft & Publish](/cms/features/draft-and-publish) is enabled, it's possible to filter based on a `published` (default) or `draft` status.
:::tip
JavaScript query (built with the qs library):
## Example: Find multiple restaurants with ids 3, 6,8
You can use the `$in` filter operator with an array of values to find multiple exact values.
JavaScript query (built with the qs library):
## Complex filtering
Complex filtering is combining multiple filters using advanced methods such as combining `$and` & `$or`. This allows for more flexibility to request exactly the data needed.
JavaScript query (built with the qs library):
## Deep filtering
Deep filtering is filtering on a relation's fields.
:::note
- Relations, media fields, components, and dynamic zones are not populated by default. Use the `populate` parameter to populate these content structures (see [`populate` documentation](/cms/api/rest/populate-select#population))
- You can filter what you populate, you can also filter nested relations, but you can't use filters for polymorphic content structures (such as media fields and dynamic zones).
:::
:::caution
Querying your API with deep filters may cause performance issues. If one of your deep filtering queries is too slow, we recommend building a custom route with an optimized version of the query.
:::
JavaScript query (built with the qs library):
# REST API Guides
Source: https://docs.strapi.io/cms/api/rest/guides/intro
# REST API Guides
The [REST API reference](/cms/api/rest) documentation is meant to provide a quick reference for all the endpoints and parameters available.
## Guides
The following guides, officially maintained by the Strapi Documentation team, cover dedicated topics and provide detailed explanations (guides indicated with 🧠) or step-by-step instructions (guides indicated with 🛠️) for some use cases:
## Additional resources
:::strapi Want to help other users?
Some of the additional resources listed in this section have been created for Strapi v4 and might not fully work with Strapi 5. If you want to update one of the following articles for Strapi 5, feel free to for the Write for the Community program.
:::
Additional tutorials and guides can be found in the following blog posts:
# Interactive Query Builder
Source: https://docs.strapi.io/cms/api/rest/interactive-query-builder
# Build your query URL with Strapi's interactive tool
A wide range of parameters can be used and combined to query your content with the [REST API](/cms/api/rest), which can result in long and complex query URLs.
Strapi's codebase uses to parse and stringify nested JavaScript objects. It's recommended to use `qs` directly to generate complex query URLs instead of creating them manually.
You can use the following interactive query builder tool to generate query URLs automatically:
1. Replace the values in the _Endpoint_ and _Endpoint Query Parameters_ fields with content that fits your needs.
2. Click the **Copy to clipboard** button to copy the automatically generated _Query String URL_ which is updated as you type.
:::info Parameters usage
Please refer to the [REST API parameters table](/cms/api/rest/parameters) and read the corresponding parameters documentation pages to better understand parameters usage.
:::
:::note
The default endpoint path is prefixed with `/api/` and should be kept as-is unless you configured a different API prefix using [the `rest.prefix` API configuration option](/cms/configurations/api). For instance, to query the `books` collection type using the default API prefix, type `/api/books` in the _Endpoint_ field.
:::
:::caution Disclaimer
The `qs` library and the interactive query builder provided on this page:
- might not detect all syntax errors,
- are not aware of the parameters and values available in a Strapi project,
- and do not provide autocomplete features.
Currently, these tools are only provided to transform the JavaScript object in an inline query string URL. Using the generated query URL does not guarantee that proper results will get returned with your API.
:::
# Locale
Source: https://docs.strapi.io/cms/api/rest/locale
# REST API: `locale`
The [Internationalization (i18n) feature](/cms/features/internationalization) adds new abilities to the [REST API](/cms/api/rest).
:::prerequisites
To work with API content for a locale, please ensure the locale has been already [added to Strapi in the admin panel](/cms/features/internationalization#settings).
:::
The `locale` [API parameter](/cms/api/rest/parameters) can be used to work with documents only for a specified locale. `locale` takes a locale code as a value (see
### `GET` Get all documents in a specific locale {#rest-get-all}
### `GET` Get a document in a specific locale {#rest-get}
To get a specific document in a given locale, add the `locale` parameter to the query:
| Use case | Syntax format and link for more information |
| -------------------- | ---------------------------------------------------------------------------------------------- |
| In a collection type | [`GET /api/content-type-plural-name/document-id?locale=locale-code`](#get-one-collection-type) |
| In a single type | [`GET /api/content-type-singular-name?locale=locale-code`](#get-one-single-type) |
#### Collection types {#get-one-collection-type}
To get a specific document in a collection type in a given locale, add the `locale` parameter to the query, after the `documentId`:
#### Single types {#get-one-single-type}
To get a specific single type document in a given locale, add the `locale` parameter to the query, after the single type name:
### `POST` Create a new localized document for a collection type {#rest-create}
To create a localized document from scratch, send a POST request to the Content API. Depending on whether you want to create it for the default locale or for another locale, you might need to pass the `locale` parameter in the query.
| Use case | Syntax format and link for more information |
| ----------------------------- | --------------------------------------------------------------------------------------- |
| Create for the default locale | [`POST /api/content-type-plural-name`](#rest-create-default-locale) |
| Create for a specific locale | [`POST /api/content-type-plural-name?locale=fr`](#rest-create-specific-locale)
#### For the default locale {#rest-create-default-locale}
If no locale has been passed in the request body, the document is created using the default locale for the application:
#### For a specific locale {#rest-create-specific-locale}
To create a localized entry for a locale different from the default one, add the `locale` parameter to the query URL of the POST request:
### `PUT` Create a new, or update an existing, locale version for an existing document {#rest-update}
With `PUT` requests sent to an existing document, you can:
- create another locale version of the document,
- or update an existing locale version of the document.
Send the `PUT` request to the appropriate URL, adding the `locale=your-locale-code` parameter to the query URL and passing attributes in a `data` object in the request's body:
| Use case | Syntax format and link for more information |
| -------------------- | --------------------------------------------------------------------------------------- |
| In a collection type | [`PUT /api/content-type-plural-name/document-id?locale=locale-code`](#rest-put-collection-type) |
| In a single type | [`PUT /api/content-type-singular-name?locale=locale-code`](#rest-put-single-type) |
:::caution
When creating a localization for existing localized entries, the body of the request can only accept localized fields.
:::
:::tip
The Content-Type should have the [`createLocalization` permission](/cms/features/rbac#collection-and-single-types) enabled, otherwise the request will return a `403: Forbidden` status.
:::
:::note
It is not possible to change the locale of an existing localized entry. When updating a localized entry, if you set a `locale` attribute in the request body it will be ignored.
:::
#### In a collection type {#rest-put-collection-type}
To create a new locale for an existing document in a collection type, add the `locale` parameter to the query, after the `documentId`, and pass data to the request's body:
#### In a single type {#rest-put-single-type}
To create a new locale for an existing single type document, add the `locale` parameter to the query, after the single type name, and pass data to the request's body:
### `DELETE` Delete a locale version of a document {#rest-delete}
To delete a locale version of a document, send a `DELETE` request with the appropriate `locale` parameter.
`DELETE` requests only send a 204 HTTP status code on success and do not return any data in the response body.
#### In a collection type {#rest-delete-collection-type}
To delete only a specific locale version of a document in a collection type, add the `locale` parameter to the query after the `documentId`:
#### In a single type {#rest-delete-single-type}
To delete only a specific locale version of a single type document, add the `locale` parameter to the query after the single type name:
# Parameters
Source: https://docs.strapi.io/cms/api/rest/parameters
# REST API parameters
API parameters can be used with the [REST API](/cms/api/rest) to filter, sort, and paginate results and to select fields and relations to populate. Additionally, specific parameters related to optional Strapi features can be used, like the publication state and locale of a content-type.
The following API parameters are available:
| Operator | Type | Description |
| ------------------ | ------------- | ----------------------------------------------------- |
| `filters` | Object | [Filter the response](/cms/api/rest/filters) |
| `locale` | String | [Select a locale](/cms/api/rest/locale) |
| `status` | String | [Select the Draft & Publish status](/cms/api/rest/status) |
| `populate` | String or Object | [Populate relations, components, or dynamic zones](/cms/api/rest/populate-select#population) |
| `fields` | Array | [Select only specific fields to display](/cms/api/rest/populate-select#field-selection) |
| `sort` | String or Array | [Sort the response](/cms/api/rest/sort-pagination.md#sorting) |
| `pagination` | Object | [Page through entries](/cms/api/rest/sort-pagination.md#pagination) |
:::note
Long bracket-encoded lists in a parameter (for example `populate` or `fields`) are limited by [`arrayLimit` on `strapi::query`](/cms/configurations/middlewares#query). See [Population](/cms/api/rest/populate-select#population).
:::
Query parameters use the (i.e. they are encoded using square brackets `[]`).
:::tip
A wide range of REST API parameters can be used and combined to query your content, which can result in long and complex query URLs. 👉 You can use Strapi's [interactive query builder](/cms/api/rest/interactive-query-builder) tool to build query URLs more conveniently. 🤗
:::
# Populate and Select
Source: https://docs.strapi.io/cms/api/rest/populate-select
# REST API: Population & Field Selection
The [REST API](/cms/api/rest) by default does not populate any relations, media fields, components, or dynamic zones. Use the [`populate` parameter](#population) to populate specific fields. Use the [`fields` parameter](#field-selection) to return only specific fields with the query results.
:::tip
## Population
The REST API by default does not populate any type of fields, so it will not populate relations, media fields, components, or dynamic zones unless you pass a `populate` parameter to populate various field types. Populated relations always return full objects; the REST API currently cannot return just an array of IDs.
:::prerequisites
The `find` permission must be enabled for the content-types that are being populated. If a role does not have access to a content-type, the content-type will not be populated (see [Users & Permissions](/cms/features/users-permissions#editing-a-role) for additional information on how to enable `find` permissions for content-types).
:::
You can use the `populate` parameter alone or [in combination with multiple operators](#combining-population-with-other-operators) for more control over the population.
:::caution
`populate=deep` plugins are [not recommended in Strapi](https://support.strapi.io/articles/8544110758-why-populate-deep-plugins-are-not-recommended-in-strapi).
:::
:::note
Large `populate` lists in the query string (many `populate[0]`, `populate[1]`, … entries) are bounded by the query parser `arrayLimit` (default: `100`). To allow a longer list, raise `arrayLimit` on the [`strapi::query` middleware](/cms/configurations/middlewares#query). Higher values increase parsing cost per request.
:::
The following table lists populate use cases with example syntax. Each row links to the Understanding populate guide for details:
| Use case | Example parameter syntax | Detailed explanations to read |
|-----------| ---------------|-----------------------|
| Populate everything, 1 level deep, including media fields, relations, components, and dynamic zones | `populate=*`| [Populate all relations and fields, 1 level deep](/cms/api/rest/guides/understanding-populate#populate-all-relations-and-fields-1-level-deep) |
| Populate one relation, 1 level deep | `populate=a-relation-name`| [Populate 1 level deep for specific relations](/cms/api/rest/guides/understanding-populate#populate-1-level-deep-for-specific-relations) |
| Populate several relations, 1 level deep | `populate[0]=relation-name&populate[1]=another-relation-name&populate[2]=yet-another-relation-name`| [Populate 1 level deep for specific relations](/cms/api/rest/guides/understanding-populate#populate-1-level-deep-for-specific-relations) |
| Populate some relations, several levels deep | `populate[root-relation-name][populate][0]=nested-relation-name`| [Populate several levels deep for specific relations](/cms/api/rest/guides/understanding-populate#populate-several-levels-deep-for-specific-relations) |
| Populate a component | `populate[0]=component-name`| [Populate components](/cms/api/rest/guides/understanding-populate#populate-components) |
| Populate a component and one of its nested components | `populate[0]=component-name&populate[1]=component-name.nested-component-name`| [Populate components](/cms/api/rest/guides/understanding-populate#populate-components) |
| Populate a dynamic zone (only its first-level elements) | `populate[0]=dynamic-zone-name`| [Populate dynamic zones](/cms/api/rest/guides/understanding-populate#populate-dynamic-zones) |
| Populate a dynamic zone and its nested elements and relations, using a precisely defined, detailed population strategy | `populate[dynamic-zone-name][on][component-category.component-name][populate][relation-name][populate][0]=field-name`| [Populate dynamic zones](/cms/api/rest/guides/understanding-populate#populate-dynamic-zones) |
:::tip
To build complex queries with multiple-level population, use the [interactive query builder](/cms/api/rest/interactive-query-builder) tool. For more detailed explanations and examples, see the [REST API guides](/cms/api/rest/guides/intro).
:::
### Combining population with other operators
You can combine the `populate` operator with other operators such as [field selection](/cms/api/rest/populate-select#field-selection), [filters](/cms/api/rest/filters), and [sort](/cms/api/rest/sort-pagination) in the population queries.
:::note
The population and pagination operators cannot be combined.
:::
#### Populate with field selection
`fields` and `populate` can be combined.
#### Populate with filtering
`filters` and `populate` can be combined.
# Relations
Source: https://docs.strapi.io/cms/api/rest/relations
# Managing relations with API requests
Defining relations between content-types (that are designated as entities in the database layers) is connecting entities with each other.
Relations between content-types can be managed through the [admin panel](/cms/features/content-manager#relational-fields) or through [REST API](/cms/api/rest) or [Document Service API](/cms/api/document-service) requests.
Relations can be connected, disconnected or set through the Content API by passing parameters in the body of the request. These payloads work for both single-entry relations and multi relations (one-to-many, many-to-one, many-to-many, and many-way). When a relational field allows multiple links, the API expects arrays of relation IDs and returns arrays in responses.
| Parameter name | Description | Type of update |
|-------------------------|-------------|----------------|
| [`connect`](#connect) | Connects new entities.
Can be used in combination with `disconnect`.
Can be used with [positional arguments](#relations-reordering) to define an order for relations. | Partial |
| [`disconnect`](#disconnect) | Disconnects entities.
Can be used in combination with `connect`. | Partial |
| [`set`](#set) | Set entities to a specific set. Using `set` will overwrite all existing connections to other entities.
Cannot be used in combination with `connect` or `disconnect`. | Full |
:::note
Multi relations can be managed from the REST API and the [GraphQL API](/cms/api/graphql#fetch-relations): the `connect`, `disconnect`, and `set` operations are available across both APIs. However, the [Document Service API](/cms/api/document-service) does not handle relations.
:::
:::note
When [Internationalization (i18n)](/cms/features/internationalization) is enabled on the content-type, you can also pass a locale to set relations for a specific locale, as in this Document Service API example:
```js
await strapi.documents('api::restaurant.restaurant').update({
documentId: 'a1b2c3d4e5f6g7h8i9j0klm',
locale: 'fr',
data: {
category: {
connect: ['z0y2x4w6v8u1t3s5r7q9onm', 'j9k8l7m6n5o4p3q2r1s0tuv']
}
}
})
```
If no locale is passed, the default locale will be assumed.
:::
## `connect`
Using `connect` in the body of a request performs a partial update, connecting the specified relations.
`connect` accepts either a shorthand or a longhand syntax:
| Syntax type | Syntax example |
| ------------|----------------|
| shorthand | `connect: ['z0y2x4w6v8u1t3s5r7q9onm', 'j9k8l7m6n5o4p3q2r1s0tuv']` |
| longhand | ```connect: [{ documentId: 'z0y2x4w6v8u1t3s5r7q9onm' }, { documentId: 'j9k8l7m6n5o4p3q2r1s0tuv' }]``` |
You can also use the longhand syntax to [reorder relations](#relations-reordering).
`connect` can be used in combination with [`disconnect`](#disconnect).
:::caution
`connect` is not officially supported for media attributes. Advanced users can technically connect media entries by targeting upload file IDs, but this workaround isn't recommended or supported by Strapi and can easily break (e.g. when Draft & Publish uses mismatched IDs). Proceed with caution.
:::
### Relations reordering
Omitting the `position` argument (as in `documentId: 'srkvrr77k96o44d9v6ef1vu9'`) defaults to `position: { end: true }`. All other relations are positioned relative to another existing `id` (using `after` or `before`) or relative to the list of relations (using `start` or `end`). Operations are treated sequentially in the order defined in the `connect` array, so the resulting database record will be the following:
```js
categories: [
{ id: 'nyk7047azdgbtjqhl7btuxw' },
{ id: 'j9k8l7m6n5o4p3q2r1s0tuv' },
{ id: '6u86wkc6x3parjd4emikhmx6' },
{ id: '3r1wkvyjwv0b9b36s7hzpxl7' },
{ id: 'a1b2c3d4e5f6g7h8i9j0klm' },
{ id: 'rkyqa499i84197l29sbmwzl' },
{ id: 'srkvrr77k96o44d9v6ef1vu9' }
]
```
### Edge cases: Draft & Publish or i18n disabled
When some built-in features of Strapi 5 are disabled for a content-type, such as [Draft & Publish](/cms/features/draft-and-publish) and [Internationalization (i18)](/cms/features/internationalization), the `connect` parameter might be used differently:
**Relation from a `Category` with i18n _off_ to an `Article` with i18n _on_:**
In this situation you can select which locale you are connecting to:
```js
data: {
categories: {
connect: [
{ documentId: 'z0y2x4w6v8u1t3s5r7q9onm', locale: 'en' },
// Connect to the same document id but with a different locale 👇
{ documentId: 'z0y2x4w6v8u1t3s5r7q9onm', locale: 'fr' },
]
}
}
```
**Relation from a `Category` with Draft & Publish _off_ to an `Article` with Draft & Publish _on_:**
```js
data: {
categories: {
connect: [
{ documentId: 'z0y2x4w6v8u1t3s5r7q9onm', status: 'draft' },
// Connect to the same document id but with different publication states 👇
{ documentId: 'z0y2x4w6v8u1t3s5r7q9onm', status: 'published' },
]
}
}
```
## `disconnect`
Using `disconnect` in the body of a request performs a partial update, disconnecting the specified relations.
`disconnect` accepts either a shorthand or a longhand syntax:
| Syntax type | Syntax example |
| ------------|----------------|
| shorthand | `disconnect: ['z0y2x4w6v8u1t3s5r7q9onm', 'j9k8l7m6n5o4p3q2r1s0tuv']`
| longhand | ```disconnect: [{ documentId: 'z0y2x4w6v8u1t3s5r7q9onm' }, { documentId: 'j9k8l7m6n5o4p3q2r1s0tuv' }]``` |
`disconnect` can be used in combination with [`connect`](#connect).
## `set`
Using `set` performs a full update, replacing all existing relations with the ones specified, in the order specified.
`set` accepts a shorthand or a longhand syntax:
| Syntax type | Syntax example |
| ----------- | ------------------------------- |
| shorthand | `set: ['z0y2x4w6v8u1t3s5r7q9onm', 'j9k8l7m6n5o4p3q2r1s0tuv']` |
| longhand | ```set: [{ documentId: 'z0y2x4w6v8u1t3s5r7q9onm' }, { documentId: 'j9k8l7m6n5o4p3q2r1s0tuv' }]``` |
As `set` replaces all existing relations, it should not be used in combination with other parameters. To perform a partial update, use [`connect`](#connect) and [`disconnect`](#disconnect).
:::note Omitting set
Omitting any parameter is equivalent to using `set`. For instance, the following 3 syntaxes are all equivalent:
- `data: { categories: set: [{ documentId: 'z0y2x4w6v8u1t3s5r7q9onm' }, { documentId: 'j9k8l7m6n5o4p3q2r1s0tuv' }] }}`
- `data: { categories: set: ['z0y2x4w6v8u1t3s5r7q9onm2', 'j9k8l7m6n5o4p3q2r1s0tuv'] }}`
- `data: { categories: ['z0y2x4w6v8u1t3s5r7q9onm2', 'j9k8l7m6n5o4p3q2r1s0tuv'] }`
:::
# Sort and Pagination
Source: https://docs.strapi.io/cms/api/rest/sort-pagination
# REST API: Sort & Pagination
Entries that are returned by queries to the [REST API](/cms/api/rest) can be sorted and paginated.
:::tip
JavaScript query (built with the qs library):
### Example: Sort using 2 fields and set the order
Using the `sort` parameter and defining `:asc` or `:desc` on sorted fields, you can get results sorted in a particular order.
JavaScript query (built with the qs library):
## Pagination
Queries can accept `pagination` parameters. Results can be paginated:
- either by [page](#pagination-by-page) (i.e., specifying a page number and the number of entries per page)
- or by [offset](#pagination-by-offset) (i.e., specifying how many entries to skip and to return)
:::note
Pagination methods can not be mixed. Always use either `page` with `pageSize` **or** `start` with `limit`.
:::
### Pagination by page
To paginate results by page, use the following parameters:
| Parameter | Type | Description | Default |
| ----------------------- | ------- | ------------------------------------------------------------------------- | ------- |
| `pagination[page]` | Integer | Page number | 1 |
| `pagination[pageSize]` | Integer | Page size | 25 |
| `pagination[withCount]` | Boolean | Adds the total numbers of entries and the number of pages to the response | True |
JavaScript query (built with the qs library):
### Pagination by offset
To paginate results by offset, use the following parameters:
| Parameter | Type | Description | Default |
| ----------------------- | ------- | -------------------------------------------------------------- | ------- |
| `pagination[start]` | Integer | Start value (i.e. first entry to return) | 0 |
| `pagination[limit]` | Integer | Number of entries to return | 25 |
| `pagination[withCount]` | Boolean | Toggles displaying the total number of entries to the response | `true` |
:::tip
The default and maximum values for `pagination[limit]` can be [configured in the `./config/api.js`](/cms/configurations/api) file with the `api.rest.defaultLimit` and `api.rest.maxLimit` keys.
:::
JavaScript query (built with the qs library):
# Status
Source: https://docs.strapi.io/cms/api/rest/status
# REST API: `status`
The [REST API](/cms/api/rest) offers the ability to filter results based on their status, draft or published.
:::prerequisites
The [Draft & Publish](/cms/features/draft-and-publish) feature should be enabled.
:::
Queries can accept a `status` parameter to fetch documents based on their status:
- `published`: returns only the published version of documents (default)
- `draft`: returns only the draft version of documents
:::tip
In the response data, the `publishedAt` field is `null` for drafts.
:::
:::note
Since published versions are returned by default, passing no status parameter is equivalent to passing `status=published`.
:::
JavaScript query (built with the qs library):
# Upload files
Source: https://docs.strapi.io/cms/api/rest/upload
# REST API: Upload files
The [Media Library feature](/cms/features/media-library) is powered in the back-end server of Strapi by the `upload` package. To upload files to Strapi, you can either use the Media Library directly from the admin panel, or use the [REST API](/cms/api/rest), with the following available endpoints :
| Method | Path | Description |
| :----- | :---------------------- | :------------------ |
| GET | `/api/upload/files` | Get a list of files |
| GET | `/api/upload/files/:id` | Get a specific file |
| POST | `/api/upload` | Upload files |
| POST | `/api/upload?id=x` | Update fileInfo |
| DELETE | `/api/upload/files/:id` | Delete a file |
:::note Notes
- [Folders](/cms/features/media-library#organizing-assets-with-folders) are an admin panel-only feature and are not part of the Content API (REST or GraphQL). Files uploaded through REST are located in the automatically created "API Uploads" folder.
- The GraphQL API does not support uploading media files. To upload files, use the REST API or directly add files from the [Media Library](/cms/features/media-library) in the admin panel. Some GraphQL mutations to update or delete uploaded media files are still possible (see [GraphQL API documentation](/cms/api/graphql#mutations-on-media-files) for details).
:::
## Upload files
Upload one or more files to your application.
`files` is the only accepted parameter, and describes the file(s) to upload. The value(s) can be a Buffer or Stream.
:::tip
When uploading an image, include a `fileInfo` object to set the file name, alt text, and caption.
:::
:::caution
You have to send FormData in your request body.
:::
## Upload entry files
Upload one or more files that will be linked to a specific entry.
The following parameters are accepted:
| Parameter | Description |
| --------- | ----------- |
|`files` | The file(s) to upload. The value(s) can be a Buffer or Stream. |
|`path` (optional) | The folder where the file(s) will be uploaded to (only supported on strapi-provider-upload-aws-s3). |
| `refId` | The ID of the entry which the file(s) will be linked to. |
| `ref` | The unique ID (uid) of the model which the file(s) will be linked to (see more below). |
| `source` (optional) | The name of the plugin where the model is located. |
| `field` | The field of the entry which the file(s) will be precisely linked to. |
For example, given the `Restaurant` model attributes:
```json title="/src/api/restaurant/content-types/restaurant/schema.json"
{
// ...
"attributes": {
"name": {
"type": "string"
},
"cover": {
"type": "media",
"multiple": false,
}
}
// ...
}
```
The following is an example of a corresponding front-end code:
```html
```
:::caution
You have to send FormData in your request body.
:::
## Update fileInfo
Update a file in your application.
`fileInfo` is the only accepted parameter, and describes the fileInfo to update:
```js
const fileId = 50;
const newFileData = {
alternativeText: 'My new alternative text for this image!',
};
const form = new FormData();
form.append('fileInfo', JSON.stringify(newFileData));
const response = await fetch(`http://localhost:1337/api/upload?id=${fileId}`, {
method: 'post',
body: form,
});
```
## Models definition
Adding a file attribute to a [model](/cms/backend-customization/models) (or the model of another plugin) is like adding a new association.
The following example lets you upload and attach one file to the `avatar` attribute:
```json title="/src/api/restaurant/content-types/restaurant/schema.json"
{
// ...
{
"attributes": {
"pseudo": {
"type": "string",
"required": true
},
"email": {
"type": "email",
"required": true,
"unique": true
},
"avatar": {
"type": "media",
"multiple": false,
}
}
}
// ...
}
```
The following example lets you upload and attach multiple pictures to the `restaurant` content-type:
```json title="/src/api/restaurant/content-types/restaurant/schema.json"
{
// ...
{
"attributes": {
"name": {
"type": "string",
"required": true
},
"covers": {
"type": "media",
"multiple": true,
}
}
}
// ...
}
```
# Back-end customization
Source: https://docs.strapi.io/cms/backend-customization
# Backend customization
:::strapi Disambiguation: Strapi back end
As a headless CMS, the Strapi software as a whole can be considered as the "back end" of your website or application.
But the Strapi software itself includes 2 different parts:
- The **back-end** part of Strapi is an HTTP server that Strapi runs. Like any HTTP server, the Strapi back end receives requests and send responses. Your content is stored in a database, and the Strapi back end interacts with the database to create, retrieve, update, and delete content.
- The **front-end** part of Strapi is called the admin panel. The admin panel presents a graphical user interface to help you structure and manage the content.
Throughout this developer documentation, 'back end' refers _exclusively_ to the back-end part of Strapi.
The [Getting Started > Admin panel page](/cms/features/admin-panel) gives an admin panel overview and the [admin panel customization section](/cms/admin-panel-customization) details the various customization options available for the admin panel.
:::
The Strapi back end runs an HTTP server based on , a back-end JavaScript framework.
Like any HTTP server, the Strapi back end receives requests and send responses. You can send requests to the Strapi back end to create, retrieve, update, or delete data through the [REST](/cms/api/rest) or [GraphQL](/cms/api/graphql) APIs.
A request can travel through the Strapi back end as follows:
1. The Strapi server receives a [request](/cms/backend-customization/requests-responses).
2. The request hits [global middlewares](/cms/backend-customization/middlewares) that are run in a sequential order.
3. The request hits a [route](/cms/backend-customization/routes). By default, Strapi generates route files for all the content-types that you create (see [REST API documentation](/cms/api/rest)), and more routes can be added and configured.
4. [Route policies](/cms/backend-customization/policies) act as a read-only validation step that can block access to a route. [Route middlewares](/cms/backend-customization/routes#middlewares) can control the request flow and mutate the request itself before moving forward.
5. [Controllers](/cms/backend-customization/controllers) execute code once a route has been reached. [Services](/cms/backend-customization/services) are optional, additional code that can be used to build custom logic reusable by controllers.
6. The code executed by the controllers and services interacts with the [models](/cms/backend-customization/models) that are a representation of the content content structure stored in the database. Interacting with the data represented by the models is handled by the [Document Service](/cms/api/document-service) and [Query Engine](/cms/api/query-engine).
7. You can implement [Document Service middlewares](/cms/api/document-service/middlewares) to control the data before it's sent to the Query Engine. The Query Engine can also use lifecycle hooks though we recommend you use Document Service middlewares unless you absolutely need to directly interact with the database.
7. The server returns a [response](/cms/backend-customization/requests-responses). The response can travel back through route middlewares and global middlewares before being sent.
Both global and route middlewares include an asynchronous callback function, `await next()`. Depending on what is returned by the middleware, the request will either go through a shorter or longer path through the back end:
* If a middleware returns nothing, the request will continue travelling through the various core elements of the back end (i.e., controllers, services, and the other layers that interact with the database).
* If a middleware returns before calling `await next()`, a response will be immediately sent, skipping the rest of the core elements. Then it will go back down the same chain it came up.
:::info
Please note that all customizations described in the pages of this section are only for the REST API. [GraphQL customizations](/cms/plugins/graphql#customization) are described in the GraphQL plugin documentation.
:::
## Interactive diagram
The following diagram represents how requests travel through the Strapi back end. You can click on any shape to jump to the relevant page in the documentation.
# Controllers
Source: https://docs.strapi.io/cms/backend-customization/controllers
# Controllers
Controllers are JavaScript files that contain a set of methods, called actions, reached by the client according to the requested [route](/cms/backend-customization/routes). Whenever a client requests the route, the action performs the business logic code and sends back the [response](/cms/backend-customization/requests-responses). Controllers represent the C in the model-view-controller (MVC) pattern.
In most cases, the controllers will contain the bulk of a project's business logic. But as a controller's logic becomes more and more complicated, it's a good practice to use [services](/cms/backend-customization/services) to organize the code into re-usable parts.
The diagram represents a simplified version of how a request travels through the Strapi back end, with controllers highlighted. The backend customization introduction page includes a complete, interactive diagram.
:::caution Sanitize inputs and outputs
When overriding core actions, always validate and sanitize queries and responses to avoid leaking private fields or bypassing access rules. Use `validateQuery` (optional), `sanitizeQuery` (recommended), and `sanitizeOutput` before returning data from custom actions. See the example below for a safe `find` override.
:::
## Implementation
Controllers can be [generated or added manually](#adding-a-new-controller). Strapi provides a `createCoreController` factory function that automatically generates core controllers and allows building custom ones or [extend or replace the generated controllers](#extending-core-controllers).
### Adding a new controller
A new controller can be implemented:
- with the [interactive CLI command `strapi generate`](/cms/cli)
- or manually by creating a JavaScript file:
- in `./src/api/[api-name]/controllers/` for API controllers (this location matters as controllers are auto-loaded by Strapi from there)
- or in a folder like `./src/plugins/[plugin-name]/server/controllers/` for plugin controllers, though they can be created elsewhere as long as the plugin interface is properly exported in the `strapi-server.js` file (see [Server API for Plugins documentation](/cms/plugins-development/server-api))
Each controller action can be an `async` or `sync` function.
Every action receives a context object (`ctx`) as a parameter. `ctx` contains the [request context](/cms/backend-customization/requests-responses#ctxrequest) and the [response context](/cms/backend-customization/requests-responses#ctxresponse).
Example: GET /hello route calling a basic controller
A specific `GET /hello` [route](/cms/backend-customization/routes) is defined, the name of the router file (i.e. `index`) is used to call the controller handler (i.e. `index`). Every time a `GET /hello` request is sent to the server, Strapi calls the `index` action in the `hello.js` controller, which returns `Hello World!`:
:::note
When a new [content-type](/cms/backend-customization/models#content-types) is created, Strapi builds a generic controller with placeholder code, ready to be customized.
:::
:::tip
To see a possible advanced usage for custom controllers, read the [services and controllers](/cms/backend-customization/examples/services-and-controllers) page of the backend customization examples cookbook.
:::
### Controllers & Routes: How routes reach controller actions
- Core mapping is automatic: when you generate a content-type, Strapi creates the matching controller and a router file that already targets the standard actions (`find`, `findOne`, `create`, `update`, and `delete`). Overriding any of these actions inside the generated controller does not require touching the router — the route keeps the same handler string and executes your updated logic.
- Adding a route should only be done for new actions or paths. If you introduce a brand-new method such as `exampleAction`, create or update a route entry whose `handler` points to the action so HTTP requests can reach it. Use the fully-qualified handler syntax `::..` (e.g. `api::restaurant.restaurant.exampleAction` for an API controller or `plugin::menus.menu.exampleAction` for a plugin controller).
- Regarding controller and route filenames: the default controller name comes from the filename inside `./src/api/[api-name]/controllers/`. Core routers created with `createCoreRouter` adopt the same name, so the generated handler string matches automatically. Custom routers can follow any file naming scheme, as long as the `handler` string references an exported controller action.
The example below adds a new controller action and exposes it through a custom route without duplicating the existing CRUD route definitions:
```js title="./src/api/restaurant/controllers/restaurant.js"
const { createCoreController } = require('@strapi/strapi').factories;
module.exports = createCoreController('api::restaurant.restaurant', ({ strapi }) => ({
async exampleAction(ctx) {
const specials = await strapi.service('api::restaurant.restaurant').find({ filters: { isSpecial: true } });
return this.transformResponse(specials.results);
},
}));
```
```js title="./src/api/restaurant/routes/01-custom-restaurant.js"
module.exports = {
routes: [
{
method: 'GET',
path: '/restaurants/specials',
handler: 'api::restaurant.restaurant.exampleAction',
},
],
};
```
### Sanitization and Validation in controllers {#sanitization-and-validation-in-controllers}
:::warning
It's strongly recommended you sanitize (v4.8.0+) and/or validate (v4.13.0+) your incoming request query utilizing the new `sanitizeQuery` and `validateQuery` functions to prevent the leaking of private data.
:::
Sanitization means that the object is “cleaned” and returned.
Validation means an assertion is made that the data is already clean and throws an error if something is found that shouldn't be there.
In Strapi 5, both query parameters and input data (i.e., create and update body data) are validated. Any create and update data requests with the following invalid input will throw a `400 Bad Request` error:
- relations the user do not have permission to create
- unrecognized values that are not present on a schema
- non-writable fields and internal timestamps like `createdAt` and `createdBy` fields
- setting or updating an `id` field (except for connecting relations)
#### Sanitization when utilizing controller factories
Within the Strapi factories the following functions are exposed that can be used for sanitization and validation:
| Function Name | Parameters | Description |
|------------------|----------------------------|--------------------------------------------------------------------------------------|
| `sanitizeQuery` | `ctx` | Sanitizes the request query |
| `sanitizeOutput` | `entity`/`entities`, `ctx` | Sanitizes the output data where entity/entities should be an object or array of data |
| `sanitizeInput` | `data`, `ctx` | Sanitizes the input data |
| `validateQuery` | `ctx` | Validates the request query (throws an error on invalid params) |
| `validateInput` | `data`, `ctx` | (EXPERIMENTAL) Validates the input data (throws an error on invalid data) |
These functions automatically inherit the sanitization settings from the model and sanitize the data accordingly based on the content-type schema and any of the content API authentication strategies, such as the Users & Permissions plugin or API tokens.
:::warning
Because these methods use the model associated with the current controller, if you query data that is from another model (i.e., doing a find for "menus" within a "restaurant" controller method), you must instead use the `strapi.contentAPI` methods, such as `strapi.contentAPI.sanitize.query` described in [Sanitizing Custom Controllers](#sanitize-validate-custom-controllers), or else the result of your query will be sanitized against the wrong model.
:::
#### Sanitization and validation when building custom controllers {#sanitize-validate-custom-controllers}
Within custom controllers, Strapi exposes the following functions via `strapi.contentAPI` for sanitization and validation. To add custom query or body parameters to Content API routes (e.g. in `register`), see [Custom Content API parameters](/cms/backend-customization/routes#custom-content-api-parameters).
| Function Name | Parameters | Description |
|------------------------------|--------------------|---------------------------------------------------------|
| `strapi.contentAPI.sanitize.input` | `data`, `schema`, `auth` | Sanitizes the request input including non-writable fields, removing restricted relations, and other nested "visitors" added by plugins |
| `strapi.contentAPI.sanitize.output` | `data`, `schema`, `auth` | Sanitizes the response output including restricted relations, private fields, passwords, and other nested "visitors" added by plugins |
| `strapi.contentAPI.sanitize.query` | `ctx.query`, `schema`, `auth` | Sanitizes the request query including filters, sort, fields, and populate |
| `strapi.contentAPI.validate.query` | `ctx.query`, `schema`, `auth` | Validates the request query including filters, sort, fields (currently not populate) |
| `strapi.contentAPI.validate.input` | `data`, `schema`, `auth` | (EXPERIMENTAL) Validates the request input including non-writable fields, removing restricted relations, and other nested "visitors" added by plugins |
:::note
Depending on the complexity of your custom controllers, you may need additional sanitization that Strapi cannot currently account for, especially when combining the data from multiple sources.
:::
### Extending core controllers {#extending-core-controllers}
Default controllers and actions are created for each content-type. These default controllers are used to return responses to API requests (e.g. when `GET /api/articles/3` is accessed, the `findOne` action of the default controller for the "Article" content-type is called). Default controllers can be customized to implement your own logic. The following code examples should help you get started.
:::tip
An action from a core controller can be replaced entirely by [creating a custom action](#adding-a-new-controller) and naming the action the same as the original action (e.g. `find`, `findOne`, `create`, `update`, or `delete`).
:::
:::tip
When extending a core controller, you do not need to re-implement any sanitization as it will already be handled by the core controller you are extending. Where possible it's strongly recommended to extend the core controller instead of creating a custom controller.
:::
Collection type examples
:::tip
The [backend customization examples cookbook](/cms/backend-customization/examples) shows how you can overwrite a default controller action, for instance for the [`create` action](/cms/backend-customization/examples/services-and-controllers#custom-controller).
:::
Single type examples
## Usage
Controllers are declared and attached to a route. Controllers are automatically called when the route is called, so controllers usually do not need to be called explicitly. However, [services](/cms/backend-customization/services) can call controllers, and in this case the following syntax should be used:
```js
// access an API controller
strapi.controller('api::api-name.controller-name');
// access a plugin controller
strapi.controller('plugin::plugin-name.controller-name');
```
:::tip
To list all the available controllers, run `yarn strapi controllers:list`.
:::
# Middlewares
Source: https://docs.strapi.io/cms/backend-customization/middlewares
# Middlewares customization
Globally scoped custom middlewares should be added to the [middlewares configuration file](/cms/configurations/middlewares#loading-order) or Strapi won't load them.
API level and plugin middlewares can be added into the specific router that they are relevant to like the following:
```js title="./src/api/[api-name]/routes/[collection-name].js or ./src/plugins/[plugin-name]/server/routes/index.js"
module.exports = {
routes: [
{
method: "GET",
path: "/[collection-name]",
handler: "[controller].find",
config: {
middlewares: ["[middleware-name]"],
// See the usage section below for middleware naming conventions
},
},
],
};
```
Example of a custom timer middleware
The GraphQL plugin also allows [implementing custom middlewares](/cms/plugins/graphql#middlewares), with a different syntax.
:::tip Discover loaded middlewares
Run `yarn strapi middlewares:list` to list all registered middlewares and double‑check naming when wiring them in routers.
:::
## Usage
Middlewares are called different ways depending on their scope:
- use `global::middleware-name` for application-level middlewares
- use `api::api-name.middleware-name` for API-level middlewares
- use `plugin::plugin-name.middleware-name` for plugin middlewares
:::tip
To list all the registered middlewares, run `yarn strapi middlewares:list`.
:::
### Restricting content access with an "is-owner policy"
It is often required that the author of an entry is the only user allowed to edit or delete the entry. In previous versions of Strapi, this was known as an "is-owner policy". With Strapi v4, the recommended way to achieve this behavior is to use a middleware.
Proper implementation largely depends on your project's needs and custom code, but the most basic implementation could be achieved with the following procedure:
1. From your project's folder, create a middleware with the Strapi CLI generator, by running the `yarn strapi generate` (or `npm run strapi generate`) command in the terminal.
2. Select `middleware` from the list, using keyboard arrows, and press Enter.
3. Give the middleware a name, for instance `isOwner`.
4. Choose `Add middleware to an existing API` from the list.
5. Select which API you want the middleware to apply.
6. Replace the code in the `/src/api/[your-api-name]/middlewares/isOwner.js` file with the following, replacing `api::restaurant.restaurant` in line 22 with the identifier corresponding to the API you choose at step 5 (e.g., `api::blog-post.blog-post` if your API name is `blog-post`):
```js showLineNumbers title="src/api/blog-post/middlewares/isOwner.js"
"use strict";
/**
* `isOwner` middleware
*/
module.exports = (config, { strapi }) => {
// Add your own logic here.
return async (ctx, next) => {
const user = ctx.state.user;
const entryId = ctx.params.id ? ctx.params.id : undefined;
let entry = {};
/**
* Gets all information about a given entry,
* populating every relations to ensure
* the response includes author-related information
*/
if (entryId) {
entry = await strapi.documents('api::restaurant.restaurant').findOne(
entryId,
{ populate: "*" }
);
}
/**
* Compares user id and entry author id
* to decide whether the request can be fulfilled
* by going forward in the Strapi backend server
*/
if (user.id !== entry.author.id) {
return ctx.unauthorized("This action is unauthorized.");
} else {
return next();
}
};
};
```
7. Ensure the middleware is configured to apply on some routes. In the `config` object found in the `src/api/[your-api–name]/routes/[your-content-type-name].js` file, define the action keys (`find`, `findOne`, `create`, `update`, `delete`, etc.) for which you would like the middleware to apply, and declare the `isOwner` middleware for these routes.
For instance, if you wish to allow GET requests (mapping to the `find` and `findOne` actions) and POST requests (i.e., the `create` action) to any user for the `restaurant` content-type in the `restaurant` API, but would like to restrict PUT (i.e., `update` action) and DELETE requests only to the user who created the entry, you could use the following code in the `src/api/restaurant/routes/restaurant.js` file:
```js title="src/api/restaurant/routes/restaurant.js"
/**
* restaurant router
*/
const { createCoreRouter } = require("@strapi/strapi").factories;
module.exports = createCoreRouter("api::restaurant.restaurant", {
config: {
update: {
middlewares: ["api::restaurant.is-owner"],
},
delete: {
middlewares: ["api::restaurant.is-owner"],
},
},
});
```
:::info
You can find more information about route middlewares in the [routes documentation](/cms/backend-customization/routes).
:::
# Models
Source: https://docs.strapi.io/cms/backend-customization/models
# Models
As Strapi is a headless Content Management System (CMS), creating a content structure for the content is one of the most important aspects of using the software. Models define a representation of the content structure.
There are 2 different types of models in Strapi:
- content-types, which can be collection types or single types, depending on how many entries they manage,
- and components that are content structures re-usable in multiple content-types.
If you are just starting out, it is convenient to generate some models with the [Content-type Builder](/cms/features/content-type-builder) directly in the admin panel. The user interface takes over a lot of validation tasks and showcases all the options available to create the content's content structure. The generated model mappings can then be reviewed at the code level using this documentation.
## Model creation
Content-types and components models are created and stored differently.
### Content-types
Content-types in Strapi can be created:
- with the [Content-type Builder in the admin panel](/cms/features/content-type-builder),
- or with [Strapi's interactive CLI `strapi generate`](/cms/cli#strapi-generate) command.
The content-types use the following files:
- `schema.json` for the model's [schema](#model-schema) definition. (generated automatically, when creating content-type with either method)
- `lifecycles.js` for [lifecycle hooks](#lifecycle-hooks). This file must be created manually.
These models files are stored in `./src/api/[api-name]/content-types/[content-type-name]/`, and any JavaScript or JSON file found in these folders will be loaded as a content-type's model (see [project structure](/cms/project-structure)).
:::note
In [TypeScript](/cms/typescript.md)-enabled projects, schema typings can be generated using the `ts:generate-types` command.
:::
### Components {#components-creation}
Component models can't be created with CLI tools. Use the [Content-type Builder](/cms/features/content-type-builder) or create them manually.
Components models are stored in the `./src/components` folder. Every component has to be inside a subfolder, named after the category the component belongs to (see [project structure](/cms/project-structure)).
## Model schema
The `schema.json` file of a model consists of:
- [settings](#model-settings), such as the kind of content-type the model represents or the table name in which the data should be stored,
- [information](#model-information), mostly used to display the model in the admin panel and access it through the REST and GraphQL APIs,
- [attributes](#model-attributes), which describe the content structure of the model,
- and [options](#model-options) used to defined specific behaviors on the model.
### Model settings
General settings for the model can be configured with the following parameters:
| Parameter | Type | Description |
| -------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------- |
| `collectionName` | String | Database table name in which the data should be stored |
| `kind`
_Optional, only for content-types_ | String | Defines if the content-type is:
a collection type (`collectionType`)
or a single type (`singleType`)
|
```json
// ./src/api/[api-name]/content-types/restaurant/schema.json
{
"kind": "collectionType",
"collectionName": "Restaurants_v1",
}
```
### Model information
The `info` key in the model's schema describes information used to display the model in the admin panel and access it through the Content API. It includes the following parameters:
| Parameter | Type | Description |
| -------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `displayName` | String | Default name to use in the admin panel |
| `singularName` | String | Singular form of the content-type name. Used to generate the API routes and databases/tables collection.
Should be kebab-case. |
| `pluralName` | String | Plural form of the content-type name. Used to generate the API routes and databases/tables collection.
Should be kebab-case. |
| `description` | String | Description of the model |
```json title="./src/api/[api-name]/content-types/restaurant/schema.json"
"info": {
"displayName": "Restaurant",
"singularName": "restaurant",
"pluralName": "restaurants",
"description": ""
},
```
### Model attributes
The content structure of a model consists of a list of attributes. Each attribute has a `type` parameter, which describes its nature and defines the attribute as a simple piece of data or a more complex structure used by Strapi.
Many types of attributes are available:
- scalar types (e.g. strings, dates, numbers, booleans, etc.),
- Strapi-specific types, such as:
- `media` for files uploaded through the [Media library](/cms/features/content-type-builder#media)
- `relation` to describe a [relation](#relations) between content-types
- `customField` to describe [custom fields](#custom-fields) and their specific keys
- `component` to define a [component](#components-json) (i.e. a content structure usable in multiple content-types)
- `dynamiczone` to define a [dynamic zone](#dynamic-zones) (i.e. a flexible space based on a list of components)
- and the `locale` and `localizations` types, only used by the [Internationalization (i18n) plugin](/cms/features/internationalization)
The `type` parameter of an attribute should be one of the following values:
| Type categories | Available types |
|------|-------|
| String types |
`string`
`text`
`richtext`
`enumeration`
`email`
`password`
[`uid`](#uid-type)
|
| Date types |
`date`
`time`
`datetime`
`timestamp`
|
| Number types |
`integer`
`biginteger`
`float`
`decimal`
|
| Other generic types |
`boolean`
`json`
|
| Special types unique to Strapi |
`media`
[`relation`](#relations)
[`customField`](#custom-fields)
[`component`](#components-json)
[`dynamiczone`](#dynamic-zones)
|
| Internationalization (i18n)-related types
_Can only be used if the [i18n](/cms/features/internationalization) is enabled on the content-type_|
`locale`
`localizations`
|
#### Validations
Basic validations can be applied to attributes using the following parameters:
| Parameter | Type | Description | Default |
| -------------- | ------- | --------------------------------------------------------------------------------------------------------- | ------- |
| `required` | Boolean | If `true`, adds a required validator for this property | `false` |
| `max` | Integer | Checks if the value is greater than or equal to the given maximum | - |
| `min` | Integer | Checks if the value is less than or equal to the given minimum | - |
| `minLength` | Integer | Minimum number of characters for a field input value | - |
| `maxLength` | Integer | Maximum number of characters for a field input value | - |
| `private` | Boolean | If `true`, the attribute will be removed from the server response.
💡 This is useful to hide sensitive data. | `false` |
| `configurable` | Boolean | If `false`, the attribute isn't configurable from the Content-type Builder plugin. | `true` |
```json title="./src/api/[api-name]/content-types/restaurant/schema.json"
{
// ...
"attributes": {
"title": {
"type": "string",
"minLength": 3,
"maxLength": 99,
"unique": true
},
"description": {
"default": "My description",
"type": "text",
"required": true
},
"slug": {
"type": "uid",
"targetField": "title"
}
// ...
}
}
```
#### Database validations and settings
:::caution 🚧 This API is considered experimental.
These settings should be reserved to an advanced usage, as they might break some features. There are no plans to make these settings stable.
:::
Database validations and settings are custom options passed directly onto the `tableBuilder` Knex.js function during schema migrations. Database validations allow for an advanced degree of control for setting custom column settings. The following options are set in a `column: {}` object per attribute:
| Parameter | Type | Description | Default |
| ------------- | ------- | --------------------------------------------------------------------------------------------- | ------- |
| `name` | string | Changes the name of the column in the database | - |
| `defaultTo` | string | Sets the database `defaultTo`, typically used with `notNullable` | - |
| `notNullable` | boolean | Sets the database `notNullable`, ensures that columns cannot be null | `false` |
| `unsigned` | boolean | Only applies to number columns, removes the ability to go negative but doubles maximum length | `false` |
| `unique` | boolean | Enforces database-level uniqueness on published entries. Draft saves skip the check when Draft & Publish is enabled, so duplicates fail only at publish time. | `false` |
| `type` | string | Changes the database type, if `type` has arguments, you should pass them in `args` | - |
| `args` | array | Arguments passed into the Knex.js function that changes things like `type` | `[]` |
:::caution Draft & Publish and `unique`
When [Draft & Publish](/cms/features/draft-and-publish) is enabled, Strapi intentionally skips `unique` validations while an entry is saved as a draft. Duplicates therefore remain undetected until publication, at which point the database constraint triggers an error even though the UI previously displayed “Saved document” for the drafts.
To avoid unexpected publication failures:
- disable Draft & Publish on content-types that must stay globally unique,
- or add custom validation (e.g. lifecycle hooks or middleware) that checks for draft duplicates before saving,
- or rely on automatically generated unique identifiers such as a `uid` field and document editorial conventions.
:::
```json title="./src/api/[api-name]/content-types/restaurant/schema.json"
{
// ...
"attributes": {
"title": {
"type": "string",
"minLength": 3,
"maxLength": 99,
"unique": true,
"column": {
"unique": true // enforce database unique also
}
},
"description": {
"default": "My description",
"type": "text",
"required": true,
"column": {
"defaultTo": "My description", // set database level default
"notNullable": true // enforce required at database level, even for drafts
}
},
"rating": {
"type": "decimal",
"default": 0,
"column": {
"defaultTo": 0,
"type": "decimal", // using the native decimal type but allowing for custom precision
"args": [
6,1 // using custom precision and scale
]
}
}
// ...
}
}
```
#### `uid` type
The `uid` type is used to automatically prefill the field value in the admin panel with a unique identifier (UID) (e.g. slugs for articles) based on 2 optional parameters:
- `targetField` (string): If used, the value of the field defined as a target is used to auto-generate the UID.
- `options` (string): If used, the UID is generated based on a set of options passed to
#### Custom fields
[Custom fields](/cms/features/custom-fields) extend Strapi’s capabilities by adding new types of fields to content-types. Custom fields are explicitly defined in the [attributes](#model-attributes) of a model with `type: customField`.
Custom fields' attributes also show the following specificities:
- a `customField` attribute whose value acts as a unique identifier to indicate which registered custom field should be used. Its value follows:
- either the `plugin::plugin-name.field-name` format if a plugin created the custom field
- or the `global::field-name` format for a custom field specific to the current Strapi application
- and additional parameters depending on what has been defined when registering the custom field (see [custom fields documentation](/cms/features/custom-fields)).
```json title="./src/api/[apiName]/[content-type-name]/content-types/schema.json"
{
// …
"attributes": {
"attributeName": { // attributeName would be replaced by the actual attribute name
"type": "customField",
"customField": "plugin::color-picker.color",
"options": {
"format": "hex"
}
}
}
// …
}
```
#### Components {#components-json}
Component fields create a relation between a content-type and a component structure. Components are explicitly defined in the [attributes](#model-attributes) of a model with `type: 'component'` and accept the following additional parameters:
| Parameter | Type | Description |
| ------------ | ------- | ---------------------------------------------------------------------------------------- |
| `repeatable` | Boolean | Could be `true` or `false` depending on whether the component is repeatable or not |
| `component` | String | Define the corresponding component, following this format: `.` |
```json title="./src/api/[apiName]/restaurant/content-types/schema.json"
{
"attributes": {
"openinghours": {
"type": "component",
"repeatable": true,
"component": "restaurant.openinghours"
}
}
}
```
#### Dynamic zones
Dynamic zones create a flexible space in which to compose content, based on a mixed list of [components](#components-json).
Dynamic zones are explicitly defined in the [attributes](#model-attributes) of a model with `type: 'dynamiczone'`. They also accept a `components` array, where each component should be named following this format: `.`.
```json title="./src/api/[api-name]/content-types/article/schema.json"
{
"attributes": {
"body": {
"type": "dynamiczone",
"components": ["article.slider", "article.content"]
}
}
}
```
### Model options
The `options` key is used to define specific behaviors and accepts the following parameter:
| Parameter | Type | Description |
|---------------------|------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `privateAttributes` | Array of strings | Allows treating a set of attributes as private, even if they're not actually defined as attributes in the model. It could be used to remove them from API responses timestamps.
The `privateAttributes` defined in the model are merged with the `privateAttributes` defined in the global Strapi configuration. |
| `draftAndPublish` | Boolean | Enables the draft and publish feature.
Default value: `true` (`false` if the content-type is created from the interactive CLI). |
| `populateCreatorFields` | Boolean | Populates `createdBy` and `updatedBy` fields in responses returned by the REST API (see [guide](/cms/api/rest/guides/populate-creator-fields) for more details).
Default value: `false`. |
```json title="./src/api/[api-name]/content-types/restaurant/schema.json"
{
"options": {
"privateAttributes": ["id", "createdAt"],
"draftAndPublish": true
}
}
```
### Plugin options
`pluginOptions` is an optional object allowing plugins to store configuration for a model or a specific attribute.
| Key | Value | Description |
|---------------------------|-------------------------------|--------------------------------------------------------|
| `i18n` | `localized: true` | Enables localization. |
| `content-manager` | `visible: false` | Hides from Content Manager in the admin panel. |
| `content-type-builder` | `visible: false` | Hides from Content-type Builder in the admin panel. |
```json title="./src/api/[api-name]/content-types/[content-type-name]/schema.json"
{
"attributes": {
"name": {
"pluginOptions": {
"i18n": {
"localized": true
}
},
"type": "string",
"required": true
},
"slug": {
"pluginOptions": {
"i18n": {
"localized": true
}
},
"type": "uid",
"targetField": "name",
"required": true
}
// …additional attributes
}
}
```
## Lifecycle hooks
Lifecycle hooks are functions that get triggered when Strapi queries are called. They are triggered automatically when managing content through the administration panel or when developing custom code using `queries`·
Lifecycle hooks can be customized declaratively or programmatically.
:::caution
Lifecycles hooks are not triggered when using directly the
Using the database layer API, it's also possible to register a subscriber and listen to events programmatically:
```js title="./src/index.js"
module.exports = {
async bootstrap({ strapi }) {
// registering a subscriber
strapi.db.lifecycles.subscribe({
models: [], // optional;
beforeCreate(event) {
const { data, where, select, populate } = event.params;
event.state = 'doStuffAfterWards';
},
afterCreate(event) {
if (event.state === 'doStuffAfterWards') {
}
const { result, params } = event;
// do something to the result
},
});
// generic subscribe for generic handling
strapi.db.lifecycles.subscribe((event) => {
if (event.action === 'beforeCreate') {
// do something
}
});
}
}
```
# Policies
Source: https://docs.strapi.io/cms/backend-customization/policies
# Policies
Policies are functions that execute specific logic on each request before it reaches the [controller](/cms/backend-customization/controllers). They are mostly used for securing business logic.
Each [route](/cms/backend-customization/routes) of a Strapi project can be associated to an array of policies. For example, a policy named `is-admin` could check that the request is sent by an admin user, and restrict access to critical routes.
Policies can be global or scoped. [Global policies](#global-policies) can be associated to any route in the project. Scoped policies only apply to a specific [API](#api-policies) or [plugin](#plugin-policies) and should live under the corresponding `./src/api//policies/` or `./src/plugins//policies/` folder.
The diagram represents a simplified version of how a request travels through the Strapi back end, with policies and routes highlighted. The backend customization introduction page includes a complete, interactive diagram.
## Implementation
A new policy can be implemented:
- with the [interactive CLI command `strapi generate`](/cms/cli#strapi-generate)
- or manually by creating a JavaScript file in the appropriate folder (see [project structure](/cms/project-structure)):
- `./src/policies/` for global policies
- `./src/api/[api-name]/policies/` for API policies
- `./src/plugins/[plugin-name]/policies/` for plugin policies
Global policy implementation example:
`policyContext` is a wrapper around the [controller](/cms/backend-customization/controllers) context. It adds some logic that can be useful to implement a policy for both REST and GraphQL.
Policies can be configured using a `config` object:
## Usage
To apply policies to a route, add them to its configuration object (see [routes documentation](/cms/backend-customization/routes#policies)).
Policies are called different ways depending on their scope:
- use `global::policy-name` for [global policies](#global-policies)
- use `api::api-name.policy-name` for [API policies](#api-policies)
- use `plugin::plugin-name.policy-name` for [plugin policies](#plugin-policies)
:::tip
To list all the available policies, run `yarn strapi policies:list`.
:::
### Global policies
Global policies can be associated to any route in a project.
### Plugin policies
Plugins can add and expose policies to an application. For example, the [Users & Permissions feature](/cms/features/users-permissions) comes with policies to ensure that the user is authenticated or has the rights to perform an action:
### API policies
API policies are associated to the routes defined in the API where they have been declared.
To use a policy in another API, reference it with the following syntax: `api::[apiName].[policyName]`:
# Requests and Responses
Source: https://docs.strapi.io/cms/backend-customization/requests-responses
# Requests and Responses
The Strapi back end server is based on . When you send requests through the [REST API](/cms/api/rest), a context object (`ctx`) is passed to every element of the Strapi back end (e.g., [policies](/cms/backend-customization/policies), [controllers](/cms/backend-customization/controllers), [services](/cms/backend-customization/services)).
`ctx` includes 3 main objects:
- [`ctx.request`](#ctxrequest) for information about the request sent by the client making an API request,
- [`ctx.state`](#ctxstate) for information about the state of the request within the Strapi back end,
- and [`ctx.response`](#ctxresponse) for information about the response that the server will return.
:::tip
The request's context can also be accessed from anywhere in the code with the [`strapi.requestContext` function](#accessing-the-request-context-anywhere).
:::
:::info
In addition to the concepts and parameters described in the following documentation, you might find additional information in the , and .
:::
The diagram represents a simplified version of how a request travels through the Strapi back end, with requests and responses highlighted. The backend customization introduction page includes a complete, interactive diagram.
## `ctx.request`
The `ctx.request` object contains the following parameters:
| Parameter | Description | Type |
| --------------------- | -------------------------------------------------------------------------------------------- | -------- |
| `ctx.request.body` | Parsed version of the body. | `Object` |
| `ctx.request.files` | Files sent with the request. | `Array` |
| `ctx.request.headers` | Headers sent with the request. | `Object` |
| `ctx.request.host` | Host part of the URL, including the port. | `String` |
| `ctx.request.hostname`| Host part of the URL, excluding the port. | `String` |
| `ctx.request.href` | Complete URL of the requested resource, including the protocol, domain, port (if specified), path, and query parameters. | `String` |
| `ctx.request.ip` | IP of the person sending the request.| `String` |
| `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.
For example if the value were "client, proxy1, proxy2", you would receive the `["client", "proxy1", "proxy2"]` array. | `Array` |
| `ctx.request.method` | Request method (e.g., `GET`, `POST`). | `String` |
| `ctx.request.origin` | URL part before the first `/`. | `String` |
| `ctx.request.params` | Parameters sent in the URL.
For example, if the internal URL is `/restaurants/:id`, whatever you replace `:id` in the real request becomes accessible through `ctx.request.params.id`. | `Object` |
| `ctx.request.path` | Path of the requested resource, excluding the query parameters. | `String` |
| `ctx.request.protocol`| Protocol being used (e.g., `https` or `http`). | `String` |
| `ctx.request.query` | Strapi-specific [query parameters](#ctxrequestquery). | `Object` |
| `ctx.request.subdomains`| Subdomains included in the URL.
For example, if the domain is `tobi.ferrets.example.com`, the value is the following array: `["ferrets", "tobi"]`. | `Array` |
| `ctx.request.url` | Path and query parameters of the requested resource, excluding the protocol, domain, and port. | `String` |
Differences between protocol, origin, url, href, path, host, and hostname :
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:
| Parameter | Returned value |
| ---------- | ------------------------------------------------- |
| `ctx.request.href` | `https://example.com:1337/api/restaurants?id=123` |
| `ctx.request.protocol` | `https` |
| `ctx.request.host` | `localhost:1337` |
| `ctx.request.hostname` | `localhost` |
| `ctx.request.origin` | `https://example.com:1337` |
| `ctx.request.url` | `/api/restaurants?id=123` |
| `ctx.request.path` | `/api/restaurants` |
### `ctx.request.query`
`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](/cms/api/rest/parameters) for more information):
| Parameter | Description | Type |
| -------------------------------------| --------------------------------------------------------------------------------------------------------------------------- | -------------------- |
| `ctx.request.query` `ctx.query` | The whole query object. | `Object` |
| `ctx.request.query.sort` | Parameters to [sort the response](/cms/api/rest/sort-pagination.md#sorting) | `String` or `Array` |
| `ctx.request.query.filters` | Parameters to [filter the response](/cms/api/rest/filters) | `Object` |
| `ctx.request.query.populate` | Parameters to [populate relations, components, or dynamic zones](/cms/api/rest/populate-select#population) | `String` or `Object` |
| `ctx.request.query.fields` | Parameters to [select only specific fields to return with the response](/cms/api/rest/populate-select#field-selection) | `Array` |
| `ctx.request.query.pagination` | Parameter to [page through entries](/cms/api/rest/sort-pagination.md#pagination) | `Object` |
| `ctx.request.query.publicationState` | Parameter to [select the Draft & Publish state](/cms/api/rest/status) | `String` |
| `ctx.request.query.locale` | Parameter to [select one or multiple locales](/cms/api/rest/locale) | `String` or `Array` |
## `ctx.state`
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):
| Parameter | Description | Type |
| ---------------------------|---------------------------------------------------------------------------- | -------- |
| `ctx.state.isAuthenticated`| Returns whether the current user is authenticated in any way. | `Boolean` |
### `ctx.state.user`
The `ctx.state.user` object gives access to information about the user performing the request and includes the following parameters:
| Parameter | Description | Type |
| ----------| -------------------------------------------------------------------------------------------- | -------- |
| `ctx.state.user`| User's information. Only one relation is populated. | `Object` |
| `ctx.state.user.role`| The user's role | `Object` |
### `ctx.state.auth`
The `ctx.state.auth` object gives access to information related to the authentication and includes the following parameters:
| Parameter | Description | Type |
| ------------------------------| -------------------------------------------------------------------------------------------- | -------- |
| `ctx.state.auth.strategy` | Information about the currently used authentication strategy ([Users & Permissions plugin](/cms/features/users-permissions) or [API tokens](/cms/features/api-tokens)) | `Object` |
| `ctx.state.auth.strategy.name`| Name of the currently used strategy | `String` |
| `ctx.state.auth.credentials` | The user's credentials | `String` |
### `ctx.state.route`
The `ctx.state.route` object gives access to information related to the current route and includes the following parameters:
| Parameter | Description | Type |
| ----------| -------------------------------------------------------------------------------------------- | -------- |
| `ctx.state.route.method`| Method used to access the current route. | `String` |
| `ctx.state.route.path`| Path of the current route. | `String` |
| `ctx.state.route.config`| Configuration information about the current route. | `Object` |
| `ctx.state.route.handler`| Handler (controller) of the current route. | `Object` |
| `ctx.state.route.info`| Additional information about the current route, such as the apiName and the API request type. | `Object` |
| `ctx.state.route.info.apiName`| Name of the used API. | `String` |
| `ctx.state.route.info.type`| Type of the used API. | `String` |
## `ctx.response`
The `ctx.response` object gives access to information related to the response that the server will return and includes the following parameters:
| Parameter | Description | Type |
| ----------| -------------------------------------------------------------------------------------------- | -------- |
| `ctx.response.body`| Body of the response. | `Any` |
| `ctx.response.status` | Status code of the response. | `Integer` |
| `ctx.response.message`| Status message of the response.
By default, `response.message` is associated with `response.status`. | `String` |
| `ctx.response.header` `ctx.response.headers`| Header(s) sent with the response. | `Object` |
| `ctx.response.length`| header value as a number when present, or deduces it from `ctx.body` when possible; otherwise, returns `undefined`. | `Integer` |
| `ctx.response.redirect` `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.
`ctx.response.attachment([filename], [options])` | Sets header to "attachment" to signal the client to prompt for download. Optionally specify the filename of the download and some . | `Function` |
| `ctx.response.type`| header, void of parameters such as "charset". | `String` |
| `ctx.response.lastModified`| header as a Date, if it exists. | `DateTime` |
| `ctx.response.etag`| Sets the of a response including the wrapped "s. There is no corresponding `response.etag` getter. | `String` |
## Accessing the request context anywhere
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:
```js
const ctx = strapi.requestContext.get();
```
You should only use this inside of functions that will be called in the context of an HTTP request.
```js
// 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:**
```js title="./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 to make the context available anywhere.
:::
# Routes
Source: https://docs.strapi.io/cms/backend-customization/routes
# Routes
Requests sent to Strapi on any URL are handled by routes. By default, Strapi generates routes for all the content-types (see [REST API documentation](/cms/api/rest)). Routes can be [added](#implementation) and configured:
- with [policies](#policies), which are a way to block access to a route,
- and with [middlewares](#middlewares), which are a way to control and change the request flow and the request itself.
Once a route exists, reaching it executes some code handled by a controller (see [controllers documentation](/cms/backend-customization/controllers)). To view all existing routes and their hierarchal order, you can run `yarn strapi routes:list` (see [CLI reference](/cms/cli)).
:::tip
If you only customize the default controller actions (`find`, `findOne`, `create`, `update`, or `delete`) that Strapi generates for a content-type, you can leave the router as-is. Those core routes already target the same handler names and will run your new controller logic. Add or edit a route only when you need a brand-new HTTP path/method or want to expose a custom controller action.
:::
The diagram represents a simplified version of how a request travels through the Strapi back end, with routes highlighted. The backend customization introduction page includes a complete, interactive diagram.
## Implementation
Implementing a new route consists in defining it in a router file within the `./src/api/[apiName]/routes` folder (see [project structure](/cms/project-structure)).
There are 2 different router file structures, depending on the use case:
- configuring [core routers](#configuring-core-routers)
- or creating [custom routers](#creating-custom-routers).
### Configuring core routers
Core routers (i.e. `find`, `findOne`, `create`, `update`, and `delete`) correspond to [default routes](/cms/api/rest#endpoints) automatically created by Strapi when a new [content-type](/cms/backend-customization/models#model-creation) is created.
Strapi provides a `createCoreRouter` factory function that automatically generates the core routers and allows:
- passing in configuration options to each router
- and disabling some core routers to [create custom ones](#creating-custom-routers).
A core router file is a JavaScript file exporting the result of a call to `createCoreRouter` with the following parameters:
| Parameter | Description | Type |
| ----------| -------------------------------------------------------------------------------------------- | -------- |
| `prefix` | Allows passing in a custom prefix to add to all routers for this model (e.g. `/test`) | `String` |
| `only` | Core routes that will only be loaded
Anything not in this array is ignored. | `Array` | -->
| `except` | Core routes that should not be loaded
This is functionally the opposite of the `only` parameter. | `Array` |
| `config` | Configuration to handle [policies](#policies), [middlewares](#middlewares) and [public availability](#public-routes) for the route | `Object` |
Generic implementation example:
This only allows a `GET` request on the `/restaurants` path from the core `find` [controller](/cms/backend-customization/controllers) without authentication. When you reference custom controller actions in custom routers, prefer the fully‑qualified `api::..` form for clarity (e.g., `api::restaurant.restaurant.review`).
### Creating custom routers
Creating custom routers consists in creating a file that exports an array of objects, each object being a route with the following parameters:
| Parameter | Description | Type |
| -------------------------- | -------------------------------------------------------------------------------- | -------- |
| `method` | Method associated to the route (i.e. `GET`, `POST`, `PUT`, `DELETE` or `PATCH`) | `String` |
| `path` | Path to reach, starting with a forward-leading slash (e.g. `/articles`)| `String` |
| `handler` | Function to execute when the route is reached. Use the fully-qualified syntax `api::api-name.controllerName.actionName` (or `plugin::plugin-name.controllerName.actionName`). The short `.` form for legacy projects also works. | `String` |
| `config`
_Optional_ | Configuration to handle [policies](#policies), [middlewares](#middlewares) and [public availability](#public-routes) for the route
| `Object` |
Dynamic routes can be created using parameters and regular expressions. These parameters will be exposed in the `ctx.params` object. For more details, please refer to the
## Configuration
Both [core routers](#configuring-core-routers) and [custom routers](#creating-custom-routers) have the same configuration options. The routes configuration is defined in a `config` object that can be used to handle [policies](#policies) and [middlewares](#middlewares) or to [make the route public](#public-routes).
### Policies
[Policies](/cms/backend-customization/policies) can be added to a route configuration:
- by pointing to a policy registered in `./src/policies`, with or without passing a custom configuration
- or by declaring the policy implementation directly, as a function that takes `policyContext` to extend
### Middlewares
[Middlewares](/cms/backend-customization/middlewares) can be added to a route configuration:
- by pointing to a middleware registered in `./src/middlewares`, with or without passing a custom configuration
- or by declaring the middleware implementation directly, as a function that takes
### Public routes
By default, routes are protected by Strapi's authentication system, which is based on [API tokens](/cms/features/api-tokens) or on the use of the [Users & Permissions plugin](/cms/features/users-permissions).
In some scenarios, it can be useful to have a route publicly available and control the access outside of the normal Strapi authentication system. This can be achieved by setting the `auth` configuration parameter of a route to `false`:
## Custom Content API parameters {#custom-content-api-parameters}
You can extend the `query` and body parameters allowed on Content API routes by registering them in the [register](/cms/configurations/functions#register) lifecycle. Registered parameters are then validated and sanitized like core parameters. Clients can send extra query keys (e.g. `?search=...`) or root-level body keys (e.g. `clientMutationId`) without requiring custom routes or controllers.
| What | Where |
|------|--------|
| Enable strict parameters (reject unknown query/body keys) | [API configuration](/cms/configurations/api): set `rest.strictParams: true` in `./config/api.js` (or `./config/api.ts`). |
| Add allowed parameters (app) | Call `addQueryParams` / `addInputParams` in [register](/cms/configurations/functions#register) in `./src/index.js` or `./src/index.ts`. |
| Add allowed parameters (plugin) | Call `addQueryParams` / `addInputParams` in the plugin's [register](/cms/plugins-development/server-lifecycle#register) lifecycle. |
When `rest.strictParams` is enabled, only core parameters and parameters on each route's request schema are accepted; the parameters you register are merged into that schema. Use the `z` instance from `@strapi/utils` (or `zod/v4`) for schemas.
### `addQueryParams`
`strapi.contentAPI.addQueryParams(options)` registers extra `query` parameters. Schemas must be scalar or array-of-scalars (string, number, boolean, enum). For nested structures, use `addInputParams` instead. Each entry can have an optional `matchRoute: (route) => boolean` callback to add the parameter only to routes for which the callback returns true. You cannot register core query param names (e.g. `filters`, `sort`, `fields`) as extra params; they are reserved.
### `addInputParams`
`strapi.contentAPI.addInputParams(options)` registers extra input parameters: root-level keys in the request body (e.g. alongside `data`), with any Zod type. The optional `matchRoute` callback works the same way as for `addQueryParams`. You cannot register reserved names such as `id` or `documentId` as input params.
### `matchRoute`
The `matchRoute` callback receives a `route` object with the following properties:
- `route.method`: the HTTP method (`'GET'`, `'POST'`, etc.)
- `route.path`: the route path
- `route.handler`: the controller action string
- `route.info`: metadata about the route
For example, to target only GET routes, use `matchRoute: (route) => route.method === 'GET'`. To target only routes whose path includes `articles`, use `matchRoute: (route) => route.path.includes('articles')`.
# Services
Source: https://docs.strapi.io/cms/backend-customization/services
# Services
Services are a set of reusable functions. They are particularly useful to respect the "don’t repeat yourself" (DRY) programming concept and to simplify [controllers](/cms/backend-customization/controllers.md) logic.
The diagram represents a simplified version of how a request travels through the Strapi back end, with services highlighted. The backend customization introduction page includes a complete, interactive diagram.
## Implementation
Services can be [generated or added manually](#adding-a-new-service). Strapi provides a `createCoreService` factory function that automatically generates core services and allows building custom ones or [extend or replace the generated services](#extending-core-services).
### Adding a new service
A new service can be implemented:
- with the [interactive CLI command `strapi generate`](/cms/cli#strapi-generate)
- or manually by creating a JavaScript file in the appropriate folder (see [project structure](/cms/project-structure.md)):
- `./src/api/[api-name]/services/` for API services
- or `./src/plugins/[plugin-name]/services/` for [plugin services](/cms/plugins-development/server-controllers-services).
To manually create a service, export a factory function that returns the service implementation (i.e. an object with methods). This factory function receives the `strapi` instance:
:::strapi Document Service API
To get started creating your own services, see Strapi's built-in functions in the [Document Service API](/cms/api/document-service) documentation.
:::
Example of a custom email service (using Nodemailer)
The goal of a service is to store reusable functions. A `sendNewsletter` service could be useful to send emails from different functions in our codebase that have a specific purpose:
The service is now available through the `strapi.service('api::restaurant.restaurant').sendNewsletter(...args)` global variable. It can be used in another part of the codebase, like in the following controller:
:::note
When a new [content-type](/cms/backend-customization/models.md#content-types) is created, Strapi builds a generic service with placeholder code, ready to be customized.
:::
### Extending core services
Core services are created for each content-type and could be used by [controllers](/cms/backend-customization/controllers.md) to execute reusable logic through a Strapi project. Core services can be customized to implement your own logic. The following code examples should help you get started.
:::tip
A core service can be replaced entirely by [creating a custom service](#adding-a-new-service) and naming it the same as the core service (e.g. `find`, `findOne`, `create`, `update`, or `delete`).
:::
Collection type examplesSingle type examples
## Usage
Once a service is created, it's accessible from [controllers](/cms/backend-customization/controllers.md) or from other services:
```js
// access an API service
strapi.service('api::apiName.serviceName').FunctionName();
// access a plugin service
strapi.service('plugin::pluginName.serviceName').FunctionName();
```
In the syntax examples above, `serviceName` is the name of the service file for API services or the name used to export the service file to `services/index.js` for plugin services.
:::tip
To list all the available services, run `yarn strapi services:list`.
:::
### Core service methods
Services generated with `createCoreService` inherit methods that wrap the [Document Service API](/cms/api/document-service). The available methods depend on the content-type:
#### Collection types
| Method | Description |
| --- | --- |
| `find(params)` | Wrapper for [`findMany`](/cms/api/document-service#findmany); returns a paginated list of documents. |
| `findOne(documentId, params)` | Wrapper for [`findOne`](/cms/api/document-service#findone); returns a single document by its `documentId`. |
| `create(params)` | Wrapper for [`create`](/cms/api/document-service#create); creates a new document. |
| `update(documentId, params)` | Wrapper for [`update`](/cms/api/document-service#update); updates an existing document. |
| `delete(documentId, params)` | Wrapper for [`delete`](/cms/api/document-service#delete); removes a document. |
| `count(params)` | Wrapper for [`count`](/cms/api/document-service#count); returns the number of matching documents. |
| `publish(documentId, params)` | Wrapper for [`publish`](/cms/api/document-service#publish); publishes a draft document. |
| `unpublish(documentId, params)` | Wrapper for [`unpublish`](/cms/api/document-service#unpublish); unpublishes a document. |
| `discardDraft(documentId, params)` | Wrapper for [`discardDraft`](/cms/api/document-service#discarddraft); deletes the draft copy. |
#### Single types
| Method | Description |
| --- | --- |
| `find(params)` | Returns the single document (uses [`findFirst`](/cms/api/document-service#findfirst) internally). |
| `createOrUpdate({ data, ...params })` | Creates the document if it doesn't exist or updates it (uses [`update`](/cms/api/document-service#update)). |
| `delete(params)` | Deletes the document (uses [`delete`](/cms/api/document-service#delete)). |
| `count(params)` | Counts documents matching the filters (uses [`count`](/cms/api/document-service#count)). |
| `publish(params)` | Publishes a draft document (uses [`publish`](/cms/api/document-service#publish)). |
| `unpublish(params)` | Unpublishes the document (uses [`unpublish`](/cms/api/document-service#unpublish)). |
| `discardDraft(params)` | Deletes the draft copy (uses [`discardDraft`](/cms/api/document-service#discarddraft)). |
#### Parameters and default behavior
Core service methods accept the same parameters as their underlying [Document Service API](/cms/api/document-service) calls, such as `fields`, `filters`, `sort`, `pagination`, `populate`, `locale`, and `status`. When no `status` is provided, Strapi automatically sets `status: 'published'` so only published content is returned. To query draft documents, explicitly pass `status: 'draft'` or another value supported by the Document Service.
The `createCoreService` factory also exposes a `getFetchParams(params)` helper that converts a controller's query object into the parameter format expected by these methods. This helper can be reused when overriding core methods to forward sanitized parameters to `strapi.documents()`.
# Webhooks
Source: https://docs.strapi.io/cms/backend-customization/webhooks
# Webhooks
Webhook is a construct used by an application to notify other applications that an event occurred. More precisely, webhook is a user-defined HTTP callback. Using a webhook is a good way to tell third-party providers to start some processing (CI, build, deployment ...).
The way a webhook works is by delivering information to a receiving application through HTTP requests (typically POST requests).
## User content-type webhooks
To prevent from unintentionally sending any user's information to other applications, Webhooks will not work for the User content-type.
If you need to notify other applications about changes in the Users collection, you can do so by creating [Lifecycle hooks](/cms/backend-customization/models#lifecycle-hooks) using the `./src/index.js` example.
## Available configurations
You can set webhook configurations inside the file `./config/server`.
- `webhooks`
- `defaultHeaders`: You can set default headers to use for your webhook requests. This option is overwritten by the headers set in the webhook itself.
**Example configuration**
## Webhooks security
Most of the time, webhooks make requests to public URLs, therefore it is possible that someone may find that URL and send it wrong information.
To prevent this from happening you can send a header with an authentication token. Using the Admin panel you would have to do it for every webhook.
Another way is to define `defaultHeaders` to add to every webhook request.
You can configure these global headers by updating the file at `./config/server`:
If you are developing the webhook handler yourself you can now verify the token by reading the headers.
### Verifying signatures
In addition to auth headers, it's recommended to sign webhook payloads and verify signatures server‑side to prevent tampering and replay attacks. To do so, you can use the following guidelines:
- Generate a shared secret and store it in environment variables
- Have the sender compute an HMAC (e.g., SHA‑256) over the raw request body plus a timestamp
- Send the signature (and timestamp) in headers (e.g., `X‑Webhook‑Signature`, `X‑Webhook‑Timestamp`)
- On receipt, recompute the HMAC and compare using a constant‑time check
- Reject if the signature is invalid or the timestamp is too old to mitigate replay
Example: Verify HMAC signatures (Node.js)
Here is a minimal Node.js middleware example (pseudo‑code) showing
Here are a few additional external examples:
-
-
## Available events
By default Strapi webhooks can be triggered by the following events:
| Name | Description |
| ----------------- | ----------------------------------------------------- |
| [`entry.create`](#entrycreate) | Triggered when a Content Type entry is created. |
| [`entry.update`](#entryupdate) | Triggered when a Content Type entry is updated. |
| [`entry.delete`](#entrydelete) | Triggered when a Content Type entry is deleted. |
| [`entry.publish`](#entrypublish) | Triggered when a Content Type entry is published.\* |
| [`entry.unpublish`](#entryunpublish) | Triggered when a Content Type entry is unpublished.\* |
| [`media.create`](#mediacreate) | Triggered when a media is created. |
| [`media.update`](#mediaupdate) | Triggered when a media is updated. |
| [`media.delete`](#mediadelete) | Triggered when a media is deleted. |
| [`review-workflows.updateEntryStage`](#review-workflowsupdateentrystage) | Triggered when content is moved between review stages (see [review workflows](/cms/features/review-workflows#configuration)). This event is only available with the edition of Strapi. |
| [`releases.publish`](#releases-publish) | Triggered when a Release is published (see [Releases](/cms/features/releases)). This event is only available with the or plan of Strapi CMS. |
\*only when `draftAndPublish` is enabled on this Content Type.
## Payloads
:::info
Private fields are not sent in the payload.
:::
### Headers
When a payload is delivered to your webhook's URL, it will contain specific headers:
| Header | Description |
| ---------------- | ------------------------------------------ |
| `X-Strapi-Event` | Name of the event type that was triggered. |
### `entry.create`
This event is triggered when a new entry is created.
**Example payload**
```json
{
"event": "entry.create",
"createdAt": "2020-01-10T08:47:36.649Z",
"model": "address",
"entry": {
"id": 1,
"geolocation": {},
"city": "Paris",
"postal_code": null,
"category": null,
"full_name": "Paris",
"createdAt": "2020-01-10T08:47:36.264Z",
"updatedAt": "2020-01-10T08:47:36.264Z",
"cover": null,
"images": []
}
}
```
### `entry.update`
This event is triggered when an entry is updated.
**Example payload**
```json
{
"event": "entry.update",
"createdAt": "2020-01-10T08:58:26.563Z",
"model": "address",
"entry": {
"id": 1,
"geolocation": {},
"city": "Paris",
"postal_code": null,
"category": null,
"full_name": "Paris",
"createdAt": "2020-01-10T08:47:36.264Z",
"updatedAt": "2020-01-10T08:58:26.210Z",
"cover": null,
"images": []
}
}
```
### `entry.delete`
This event is triggered when an entry is deleted.
**Example payload**
```json
{
"event": "entry.delete",
"createdAt": "2020-01-10T08:59:35.796Z",
"model": "address",
"entry": {
"id": 1,
"geolocation": {},
"city": "Paris",
"postal_code": null,
"category": null,
"full_name": "Paris",
"createdAt": "2020-01-10T08:47:36.264Z",
"updatedAt": "2020-01-10T08:58:26.210Z",
"cover": null,
"images": []
}
}
```
### `entry.publish`
This event is triggered when an entry is published.
**Example payload**
```json
{
"event": "entry.publish",
"createdAt": "2020-01-10T08:59:35.796Z",
"model": "address",
"entry": {
"id": 1,
"geolocation": {},
"city": "Paris",
"postal_code": null,
"category": null,
"full_name": "Paris",
"createdAt": "2020-01-10T08:47:36.264Z",
"updatedAt": "2020-01-10T08:58:26.210Z",
"publishedAt": "2020-08-29T14:20:12.134Z",
"cover": null,
"images": []
}
}
```
### `entry.unpublish`
This event is triggered when an entry is unpublished.
**Example payload**
```json
{
"event": "entry.unpublish",
"createdAt": "2020-01-10T08:59:35.796Z",
"model": "address",
"entry": {
"id": 1,
"geolocation": {},
"city": "Paris",
"postal_code": null,
"category": null,
"full_name": "Paris",
"createdAt": "2020-01-10T08:47:36.264Z",
"updatedAt": "2020-01-10T08:58:26.210Z",
"publishedAt": null,
"cover": null,
"images": []
}
}
```
### `media.create`
This event is triggered when you upload a file on entry creation or through the media interface.
**Example payload**
```json
{
"event": "media.create",
"createdAt": "2020-01-10T10:58:41.115Z",
"media": {
"id": 1,
"name": "image.png",
"hash": "353fc98a19e44da9acf61d71b11895f9",
"sha256": "huGUaFJhmcZRHLcxeQNKblh53vtSUXYaB16WSOe0Bdc",
"ext": ".png",
"mime": "image/png",
"size": 228.19,
"url": "/uploads/353fc98a19e44da9acf61d71b11895f9.png",
"provider": "local",
"provider_metadata": null,
"createdAt": "2020-01-10T10:58:41.095Z",
"updatedAt": "2020-01-10T10:58:41.095Z",
"related": []
}
}
```
### `media.update`
This event is triggered when you replace a media or update the metadata of a media through the media interface.
**Example payload**
```json
{
"event": "media.update",
"createdAt": "2020-01-10T10:58:41.115Z",
"media": {
"id": 1,
"name": "image.png",
"hash": "353fc98a19e44da9acf61d71b11895f9",
"sha256": "huGUaFJhmcZRHLcxeQNKblh53vtSUXYaB16WSOe0Bdc",
"ext": ".png",
"mime": "image/png",
"size": 228.19,
"url": "/uploads/353fc98a19e44da9acf61d71b11895f9.png",
"provider": "local",
"provider_metadata": null,
"createdAt": "2020-01-10T10:58:41.095Z",
"updatedAt": "2020-01-10T10:58:41.095Z",
"related": []
}
}
```
### `media.delete`
This event is triggered only when you delete a media through the media interface.
**Example payload**
```json
{
"event": "media.delete",
"createdAt": "2020-01-10T11:02:46.232Z",
"media": {
"id": 11,
"name": "photo.png",
"hash": "43761478513a4c47a5fd4a03178cfccb",
"sha256": "HrpDOKLFoSocilA6B0_icA9XXTSPR9heekt2SsHTZZE",
"ext": ".png",
"mime": "image/png",
"size": 4947.76,
"url": "/uploads/43761478513a4c47a5fd4a03178cfccb.png",
"provider": "local",
"provider_metadata": null,
"createdAt": "2020-01-07T19:34:32.168Z",
"updatedAt": "2020-01-07T19:34:32.168Z",
"related": []
}
}
```
### `review-workflows.updateEntryStage`
This event is only available with the plan of Strapi. The event is triggered when content is moved to a new review stage (see [Review Workflows](/cms/features/review-workflows#configuration)).
**Example payload**
```json
{
"event": "review-workflows.updateEntryStage",
"createdAt": "2023-06-26T15:46:35.664Z",
"model": "model",
"uid": "uid",
"entity": {
"id": 2
},
"workflow": {
"id": 1,
"stages": {
"from": {
"id": 1,
"name": "Stage 1"
},
"to": {
"id": 2,
"name": "Stage 2"
}
}
}
}
```
### `releases.publish` {#releases-publish}
The event is triggered when a [release](/cms/features/releases) is published.
**Example payload**
```json
{
"event": "releases.publish",
"createdAt": "2024-02-21T16:45:36.877Z",
"isPublished": true,
"release": {
"id": 2,
"name": "Fall Winter highlights",
"releasedAt": "2024-02-21T16:45:36.873Z",
"scheduledAt": null,
"timezone": null,
"createdAt": "2024-02-21T15:16:22.555Z",
"updatedAt": "2024-02-21T16:45:36.875Z",
"actions": {
"count": 1
}
}
}
```
## Best practices for webhook handling
- Validate incoming requests by checking headers and payload signatures.
- Implement retries for failed webhook requests to handle transient errors.
- Log webhook events for debugging and monitoring.
- Use secure, HTTPS endpoints for receiving webhooks.
- Set up rate limiting to avoid being overwhelmed by multiple webhook requests.
:::tip
If you want to learn more about how to use webhooks with Next.js, please have a look at the [dedicated blog article](https://strapi.io/blog/how-to-create-an-ssg-static-site-generation-application-with-strapi-webhooks-and-nextjs).
:::
# Command Line Interface
Source: https://docs.strapi.io/cms/cli
# Command Line Interface (CLI)
Strapi comes with a full featured Command Line Interface (CLI) which lets you scaffold and manage your project in seconds. The CLI works with both the `yarn` and `npm` package managers.
:::caution
Interactive commands such as `strapi admin:create-user` don't display prompts with `npm`. Please consider using the `yarn` package manager.
:::
:::note
It is recommended to install Strapi locally only, which requires prefixing all of the following `strapi` commands with the package manager used for the project setup (e.g `npm run strapi help` or `yarn strapi help`) or a dedicated node package executor (e.g. `npx strapi help`).
To pass options with `npm` use the syntax: `npm run strapi -- --