Strapi Patterns
Quick Guide: Use Strapi as an open-source headless CMS with auto-generated REST/GraphQL APIs from content type schemas. In v5, use the Document Service API (
strapi.documents()) for back-end data access instead of the deprecated Entity Service. REST API responses use a flat format (data.fieldName, notdata.attributes.fieldName). Relations and media are NOT populated by default -- always passpopulate. Useqsto build complex query strings. Content types are private by default; configure permissions via the Users & Permissions plugin or API tokens.
<critical_requirements>
CRITICAL: Before Using This Skill
All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering,
import type, named constants)
(You MUST use strapi.documents('api::content-type.content-type') (Document Service API) for all back-end data access in Strapi v5 -- the Entity Service API is removed)
(You MUST always pass populate when you need relations, media, components, or dynamic zones -- Strapi returns NO relations by default)
(You MUST use the qs library to build complex REST API query strings with filters, populate, and sort -- manual string construction breaks with nested params)
(You MUST sanitize and validate both input and output in custom controllers using this.sanitizeQuery(ctx), this.sanitizeOutput(), and this.validateQuery(ctx))
(You MUST set permissions for every content type endpoint via the admin panel or config -- all routes are private by default)
</critical_requirements>
Auto-detection: Strapi, strapi, @strapi/strapi, createCoreController, createCoreService, createCoreRouter, Document Service, strapi.documents, content-type, schema.json, api::, plugin::, lifecycle hooks, Users & Permissions, /api/auth/local, populate, qs.stringify
When to use:
- Building content-managed applications with Strapi as the headless CMS
- Defining content type schemas (
schema.json) with fields, relations, components, and dynamic zones - Querying the REST API with filters, populate, sort, and pagination
- Creating custom controllers, services, routes, policies, or middlewares
- Using the Document Service API for back-end CRUD with draft/publish workflows
- Implementing JWT authentication with the Users & Permissions plugin
- Adding lifecycle hooks to content types for side effects
- Generating TypeScript types for content schemas
Key patterns covered:
- Content type schema definition (
schema.json) - REST API querying with
qs(filters, populate, sort, pagination) - Document Service API (
findMany,findOne,create,update,delete,publish,unpublish) - Custom controllers, services, routes, policies, and middlewares
- Lifecycle hooks (
beforeCreate,afterUpdate, etc.) - JWT authentication (register, login, authenticated requests)
- TypeScript type generation
When NOT to use:
- Non-Strapi CMS platforms (use the dedicated skill for your CMS)
- Direct database queries bypassing Strapi's API layer (use Strapi's Document Service)
- Complex transactional logic requiring raw SQL (Strapi abstracts the database)
Detailed Resources:
- For decision frameworks and quick-reference tables, see reference.md
Core & REST API:
- examples/core.md -- Content type schemas, REST API querying, Document Service API, error handling
Backend Customization:
- examples/backend.md -- Custom controllers, services, routes, policies, middlewares, lifecycle hooks, Document Service middleware
Authentication:
- examples/auth.md -- JWT authentication, registration, login, roles and permissions
<philosophy>
Philosophy
Strapi is an open-source headless CMS built on Node.js (Koa) that auto-generates RESTful and GraphQL APIs from content type schemas. Content is defined via JSON schemas, managed through an admin panel, and consumed via generated API endpoints.
Core principles:
- Schema-driven content -- Content types are defined in
schema.jsonfiles that describe fields, relations, components, and dynamic zones. The admin panel Content-Type Builder provides a visual editor, but schemas are code that lives in your repository. - Auto-generated APIs -- Every content type automatically gets CRUD REST endpoints (
/api/:pluralApiId) and optional GraphQL support. No manual route/controller creation needed for standard operations. - Document Service API (v5) -- The back-end API for accessing content from custom code, plugins, and lifecycle hooks. Replaces v4's Entity Service. Uses
documentId(not databaseid) as the primary identifier. - Draft & Publish -- Content types can have draft/publish workflows. The Document Service defaults to
status: 'draft'; published content requiresstatus: 'published'or explicitpublish()calls. - Permission-first -- All content type endpoints are private by default. Access must be explicitly granted via the admin panel (Users & Permissions plugin) or API tokens.
- Backend customization -- Controllers, services, routes, policies, and middlewares can all be customized. Strapi follows an MVC-like pattern built on Koa.
<patterns>
Core Patterns
Pattern 1: Content Type Schema
Content types are defined in schema.json files at ./src/api/[api-name]/content-types/[content-type-name]/schema.json. Use collectionType for multi-document content (articles, products) and singleType for single-document content (site settings, homepage).
{
"kind": "collectionType",
"info": {
"singularName": "article",
"pluralName": "articles",
"displayName": "Article"
},
"options": { "draftAndPublish": true },
"attributes": {
"title": { "type": "string", "required": true },
"slug": { "type": "uid", "targetField": "title" },
"author": {
"type": "relation",
"relation": "manyToOne",
"target": "api::author.author",
"inversedBy": "articles"
},
"blocks": {
"type": "dynamiczone",
"components": ["blocks.hero", "blocks.rich-text"]
}
}
}
Key fields: uid auto-generates slugs from targetField, relation types define cardinality with inversedBy/mappedBy, component embeds reusable blocks, dynamiczone allows mixed component types. See examples/core.md for full collection and single type examples.
Pattern 2: REST API Querying with qs
The REST API accepts complex query parameters for filtering, population, sorting, and pagination. Always use the qs library to build query strings.
import qs from "qs";
const query = qs.stringify(
{
filters: { publishedAt: { $notNull: true } },
populate: {
author: { fields: ["name"] },
categories: { fields: ["name", "slug"] },
},
sort: ["publishedAt:desc"],
pagination: { page: 1, pageSize: 25 },
},
{ encodeValuesOnly: true },
);
const response = await fetch(`${STRAPI_URL}/api/articles?${query}`);
const { data, meta } = await response.json();
Key points: encodeValuesOnly prevents bracket encoding issues, filters use operators ($eq, $notNull, $containsi, $or, $and), targeted populate with fields avoids over-fetching (never use populate=* in production), dynamic zone components use on syntax. See examples/core.md for full filtering, population, and pagination examples.
Pattern 3: Document Service API (Back-End)
The Document Service API is used in custom controllers, services, lifecycle hooks, and plugins to access content from the server side. It replaces v4's Entity Service (removed in v5).
const CONTENT_TYPE_UID = "api::article.article";
// Find published content (default is 'draft')
const articles = await strapi.documents(CONTENT_TYPE_UID).findMany({
status: "published",
filters: