### Local Plugin Configuration Example Source: https://docs.strapi.io/cms/plugins-development/create-a-plugin Example configuration for a locally developed Strapi plugin in the `/config/plugins.js` or `/config/plugins.ts` file. This setup is necessary when not using the Plugin SDK directly. ```javascript myplugin: { enabled: true, resolve: './src/plugins/local-plugin', } ``` -------------------------------- ### GET /hello Source: https://docs.strapi.io/cms/backend-customization/controllers A simple example of a controller action that returns 'Hello World!'. This is a basic GET request to the /hello endpoint. ```APIDOC ## GET /hello ### Description This endpoint returns a simple 'Hello World!' message. It demonstrates a basic controller action. ### Method GET ### Endpoint /hello ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **message** (string) - The greeting message. #### Response Example ``` "Hello World!" ``` ``` -------------------------------- ### Create Strapi App with SQLite (Quickstart) Source: https://docs.strapi.io/cms/configurations/database Commands to create a new Strapi application with SQLite pre-configured for local development. This is the quickest way to start a new project locally. ```bash yarn create strapi-app my-project --quickstart ``` ```bash npx create-strapi-app@latest my-project --quickstart ``` -------------------------------- ### Configure Windows Start Script (NPM) Source: https://docs.strapi.io/cms/deployment Adds a script to package.json to start the Strapi server in production mode on Windows. It uses 'cross-env' to set the NODE_ENV to 'production'. ```json "start:win": "cross-env NODE_ENV=production npm start" ``` -------------------------------- ### Example .env File for Strapi Configuration Source: https://docs.strapi.io/cms/deployment This example illustrates how to set environment variables directly in a `.env` file for Strapi configuration. It shows overriding default host and port settings, which is a common practice for local development and simpler deployments. Ensure this file is kept secure and not committed to public repositories. ```env HOST=10.0.0.1 PORT=1338 ``` -------------------------------- ### Strapi TypeScript Configuration Source: https://context7_llms This documentation covers getting started with TypeScript for your Strapi application. It outlines the necessary configurations and best practices for using TypeScript with Strapi. ```typescript // tsconfig.json (example) { "compilerOptions": { "target": "es2017", "module": "commonjs", "lib": ["es2017"], "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "outDir": "./dist" }, "include": [ "src/**/*.ts" ], "exclude": [ "node_modules", "dist" ] } // src/index.ts (example) import strapi from '@strapi/strapi'; async function bootstrap() { await strapi.boot(); strapi.server.load({ routes: { prefix: '/api', }, }); await strapi.start(); } bootstrap().catch(err => { console.error(err); process.exit(1); }); ``` -------------------------------- ### Install Strapi Client with Package Managers Source: https://docs.strapi.io/cms/api/client Instructions for installing the Strapi Client library using Yarn, NPM, and pnpm. This is a prerequisite for using the client in your project. ```yarn yarn add @strapi/client ``` ```npm npm install @strapi/client ``` ```pnpm pnpm add @strapi/client ``` -------------------------------- ### Install SQLite Driver for Strapi Source: https://docs.strapi.io/cms/configurations/database Commands to install the 'better-sqlite3' package, which is required for using SQLite as the database client in Strapi. This is necessary for manual SQLite setup. ```bash yarn add better-sqlite3 ``` ```bash npm install better-sqlite3 ``` -------------------------------- ### Custom Controller Action Example Source: https://docs.strapi.io/cms/backend-customization/controllers Example demonstrating how to add a custom controller action ('exampleAction') and expose it via a new route ('/restaurants/specials'). ```APIDOC ## Custom Restaurant Specials API ### Description This endpoint retrieves a list of special restaurant items. It showcases how to define a custom controller action and link it to a specific route. ### Method GET ### Endpoint /restaurants/specials ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **specials** (array) - A list of special restaurant items. #### Response Example ```json { "data": [ { "id": 1, "attributes": { "name": "Special Dish 1", "isSpecial": true // ... other attributes } } // ... more specials ] } ``` ``` -------------------------------- ### Manage Strapi Instance for Testing Source: https://docs.strapi.io/cms/testing Provides functions to initialize, start, and manage a Strapi instance for testing purposes. It includes logic for registering a test route and optionally seeding example data. ```javascript let instance; async function setupStrapi() { if (!instance) { instance = await createStrapi().load(); const contentApi = instance.server?.api?.('content-api'); if (contentApi && !instance.__helloRouteRegistered) { const createHelloService = require(path.join( __dirname, '..', 'src', 'api', 'hello', 'services', 'hello' )); const helloService = createHelloService({ strapi: instance }); contentApi.routes([ { method: 'GET', path: '/hello', handler: async (ctx) => { ctx.body = await helloService.getMessage(); }, config: { auth: false, }, }, ]); contentApi.mount(instance.server.router); instance.__helloRouteRegistered = true; } await instance.start(); global.strapi = instance; if (process.env.TEST_SEED === 'true') { try { const { seedExampleApp } = require(path.join(__dirname, '..', 'scripts', 'seed')); await seedExampleApp(); } catch (e) { console.warn('Seeding failed:', e); } } } } ``` -------------------------------- ### Install Strapi GraphQL Plugin Source: https://docs.strapi.io/cms/api/graphql Installs the Strapi GraphQL plugin using either Yarn or NPM. This plugin is required to use the GraphQL API for interacting with your content types. ```bash yarn add @strapi/plugin-graphql ``` ```bash npm install @strapi/plugin-graphql ``` -------------------------------- ### Get Plugin Settings from Strapi Store (JavaScript) Source: https://docs.strapi.io/cms/configurations/database Example of retrieving specific settings from Strapi's store for a plugin. It demonstrates how to create a reusable store variable and fetch a key. ```javascript // create reusable plugin store variable const pluginStore = strapi.store({ environment: strapi.config.environment, type: 'plugin', name: 'users-permissions', }); await pluginStore.get({ key: 'grant' }); ``` -------------------------------- ### Install Jest and Supertest for Testing Source: https://docs.strapi.io/cms/testing Installs Jest for test running and Supertest for HTTP API testing as development dependencies. Jest provides assertion utilities, while Supertest allows testing API routes as if they were instances of http.Server. ```bash yarn add jest supertest --dev ``` ```bash npm install jest supertest --save-dev ``` -------------------------------- ### Configure Email Provider in Strapi (TypeScript - Generic Example) Source: https://docs.strapi.io/cms/features/email A generic TypeScript example for configuring an email provider in Strapi. This snippet shows the structure for provider options and settings, with a placeholder for a 'sendmail' provider. ```typescript export default ({ env }) => ({ email: { config: { provider: 'sendmail', // replace with your provider providerOptions: { // ... provider-specific options }, settings: { defaultFrom: 'no-reply@example.com', defaultReplyTo: 'support@example.com', }, }, }, }); ``` -------------------------------- ### Install Email Provider using Yarn Source: https://docs.strapi.io/cms/features/email Installs the Sendgrid email provider for Strapi using the Yarn package manager. This command adds the necessary package to your project's dependencies. ```bash yarn add @strapi/provider-email-sendgrid ``` -------------------------------- ### Install Strapi GraphQL Plugin (Yarn) Source: https://docs.strapi.io/cms/plugins/graphql Installs the Strapi GraphQL plugin using Yarn. This command adds the necessary package to your project's dependencies. ```bash yarn add @strapi/plugin-graphql ``` -------------------------------- ### Install Strapi GraphQL Plugin (NPM) Source: https://docs.strapi.io/cms/plugins/graphql Installs the Strapi GraphQL plugin using NPM. This command adds the necessary package to your project's dependencies. ```bash npm install @strapi/plugin-graphql ``` -------------------------------- ### Strapi Admin Entry Point Setup (JavaScript) Source: https://docs.strapi.io/cms/plugins-development/create-a-plugin Sets up a Strapi plugin within the admin panel by exporting an object with methods for registration, bootstrapping, and handling translations. This is typically defined in `strapi-admin.js`. ```javascript export default { register(app) {}, bootstrap() {}, registerTrads({ locales }) {}, }; ``` -------------------------------- ### Strapi Project Setup: Templates Source: https://context7_llms Templates allow bootstrapping new Strapi projects with pre-configured structures using CLI flags like --template. Any Strapi project can be converted into a reusable template. ```bash npx create-strapi-app my-project --template my-template-repo npx create-strapi-app my-project --template-path ./path/to/local/template npx create-strapi-app my-project --template-branch main ``` -------------------------------- ### Run Server in Production (NPM) Source: https://docs.strapi.io/cms/deployment Starts the Strapi server in production mode using NPM. Sets the NODE_ENV environment variable to 'production' before executing the start command. ```shell NODE_ENV=production npm run start ``` -------------------------------- ### Run Server in Production (Yarn) Source: https://docs.strapi.io/cms/deployment Starts the Strapi server in production mode using Yarn. Sets the NODE_ENV environment variable to 'production' before executing the start command. ```shell NODE_ENV=production yarn start ``` -------------------------------- ### Accessing Strapi Features via Getters (Examples) Source: https://docs.strapi.io/cms/plugins-development/server-api This section provides examples of how to access various Strapi features, such as controllers, services, and configurations, using both top-level and global getter syntaxes. These methods allow interaction with different parts of the Strapi application. ```javascript // Access an API or a plugin controller using a top-level getter strapi.api['api-name'].controller('controller-name') strapi.plugin('plugin-name').controller('controller-name') // Access an API or a plugin controller using a global getter strapi.controller('api::api-name.controller-name') strapi.controller('plugin::plugin-name.controller-name') ``` ```javascript strapi.plugin('plugin-name').config strapi.plugin('plugin-name').routes strapi.plugin('plugin-name').controller('controller-name') strapi.plugin('plugin-name').service('service-name') strapi.plugin('plugin-name').contentType('content-type-name') strapi.plugin('plugin-name').policy('policy-name') strapi.plugin('plugin-name').middleware('middleware-name') ``` ```javascript strapi.controller('plugin::plugin-name.controller-name'); strapi.service('plugin::plugin-name.service-name'); strapi.contentType('plugin::plugin-name.content-type-name'); strapi.policy('plugin::plugin-name.policy-name'); strapi.middleware('plugin::plugin-name.middleware-name'); ``` -------------------------------- ### Get Sentry Instance (JavaScript) Source: https://docs.strapi.io/cms/plugins/sentry Provides an example of how to get direct access to the Sentry instance within a Strapi application using the `getInstance` method from the Sentry service. ```javascript const sentryInstance = strapi .plugin('sentry') .service('sentry') .getInstance(); ``` -------------------------------- ### Paginate Results with Document Service API Source: https://docs.strapi.io/cms/api/document-service/sort-pagination Paginate query results from the Document Service API by specifying the 'limit' and 'start' parameters. This example retrieves 10 documents starting from the first record (index 0). ```javascript const documents = await strapi.documents("api::article.article").findMany({ limit: 10, start: 0, }); ``` -------------------------------- ### Strapi Template Usage Syntax Examples Source: https://docs.strapi.io/cms/templates This section illustrates various syntaxes for specifying Strapi templates during application creation. It covers using Strapi-maintained templates by name, GitHub repository shorthands with or without subpaths, full repository URLs, and explicit branch and path definitions. ```bash --template website --template strapi/strapi --template strapi/strapi/some/sub/path --template strapi/strapi \ --template-branch=xxx \ --template-path=some/sub/path --template https://github.com/owner/some-template-repo --template https://github.com/owner/some-template-repo --template-branch=xxx --template-path=sub/path --template https://github.com/strapi/strapi/tree/branch/sub/path ``` -------------------------------- ### Strapi Cloud Dashboard Deployment Guide Source: https://docs.strapi.io/cloud/getting-started/deployment This section describes the process of deploying a Strapi project using the Strapi Cloud dashboard. It outlines prerequisites such as Strapi version, database compatibility (PostgreSQL recommended), and source code hosting on GitHub or GitLab. It also details the login process via GitHub, Google, GitLab, or Magic Link, and the steps to create a new project from the Projects page. ```markdown Project deployment with the Cloud dashboard =========================================== This is a step-by-step guide for deploying your project on Strapi Cloud for the first time, using the Cloud dashboard. Prerequisites Before you can deploy your Strapi application on Strapi Cloud using the Cloud dashboard, you need to have the following prerequisites: * Strapi version `4.8.2` or higher * Project database must be compatible with PostgreSQL. Strapi does not support and does not recommend using any external databases, though it's possible to configure one (see [advanced database configuration](/cloud/advanced/database)). * Project source code hosted on [GitHub](https://github.com) or [GitLab](https://about.gitlab.com/). The connected repository can contain multiple Strapi applications. Each Strapi app must be in a separate directory. * Specifically for GitLab: at least have "[Maintainer](https://docs.gitlab.com/ee/user/permissions.html)" permissions for the project to import on Strapi Cloud. Logging in to Strapi Cloud[​](#logging-in-to-strapi-cloud "Direct link to Logging in to Strapi Cloud") ------------------------------------------------------------------------------------------------------ 1. Navigate to the [Strapi Cloud](https://cloud.strapi.io) login page. 2. You have the options to **Log in with GitHub**, **Log in with Google**, **Log in with GitLab** or **Magic link**. Choose your preferred option and log in. This initial login will create your Strapi Cloud account. Once logged in, you will be redirected to the Strapi Cloud _Projects_ page where you can create your first Strapi Cloud project. Creating a project[​](#deploying-a-project "Direct link to Creating a project") ------------------------------------------------------------------------------- 1. From the _Projects_ page, click the **Create project** button. ``` -------------------------------- ### User Signup Controller in JavaScript Source: https://docs.strapi.io/cms/backend-customization/services Handles user signup by adding a new user to the database and sending a welcome email. It uses Strapi's service layer for user management and email notifications. ```javascript module.exports = createCoreController('api::restaurant.restaurant', ({ strapi }) => ({ // GET /hello async signup(ctx) { const { userData } = ctx.body; // Store the new user in database. const user = await strapi.service('plugin::users-permissions.user').add(userData); // Send an email to validate his subscriptions. strapi.service('api::restaurant.restaurant').sendNewsletter('welcome@mysite.com', user.email, 'Welcome', '...'); // Send response to the server. ctx.send({ ok: true, }); },})); ``` -------------------------------- ### Implement Custom Email Service with Nodemailer (JavaScript & TypeScript) Source: https://docs.strapi.io/cms/backend-customization/services Shows how to create a custom service for sending emails using Nodemailer. This service can be reused across the codebase. It requires Nodemailer to be installed (`npm install nodemailer`). The example defines a `sendNewsletter` function that takes sender, recipient, subject, and text as arguments. ```javascript const { createCoreService } = require('@strapi/strapi').factories; const nodemailer = require('nodemailer'); // Requires nodemailer to be installed (npm install nodemailer) // Create reusable transporter object using SMTP transport. const transporter = nodemailer.createTransport({ service: 'Gmail', auth: { user: 'user@gmail.com', pass: 'password', }, }); module.exports = createCoreService('api::restaurant.restaurant', ({ strapi }) => ({ sendNewsletter(from, to, subject, text) { // Setup e-mail data. const options = { from, to, subject, text, }; // Return a promise of the function that sends the email. return transporter.sendMail(options); }, })); ``` ```typescript import { factories } from '@strapi/strapi'; const nodemailer = require('nodemailer'); // Requires nodemailer to be installed (npm install nodemailer) // Create reusable transporter object using SMTP transport. const transporter = nodemailer.createTransport({ service: 'Gmail', auth: { user: 'user@gmail.com', pass: 'password', }, }); export default factories.createCoreService('api::restaurant.restaurant', ({ strapi }) => ({ sendNewsletter(from, to, subject, text) { // Setup e-mail data. const options = { from, to, subject, text, }; // Return a promise of the function that sends the email. return transporter.sendMail(options); }, })); ``` -------------------------------- ### Initialize Strapi Client in JavaScript Source: https://docs.strapi.io/cms/api/client Demonstrates how to initialize the Strapi Client in JavaScript by importing the 'strapi' function and creating a client instance with the base API URL. ```javascript import { strapi } from '@strapi/client'; const client = strapi({ baseURL: 'http://localhost:1337/api' }); ``` -------------------------------- ### GET /api/articles - Pagination by Offset Source: https://docs.strapi.io/cms/api/rest/sort-pagination This endpoint allows you to retrieve a list of articles with pagination controlled by offset. You can specify the starting entry and the number of entries to return. ```APIDOC ## GET /api/articles ### Description Retrieves a list of articles with offset-based pagination. ### Method GET ### Endpoint /api/articles ### Query Parameters - **pagination[start]** (integer) - Optional - The starting index of the entries to return. Defaults to 0. - **pagination[limit]** (integer) - Optional - The maximum number of entries to return. Defaults to 25. - **pagination[withCount]** (boolean) - Optional - Toggles the inclusion of the total number of entries in the response. Defaults to true. ### Request Example `GET /api/articles?pagination[start]=0&pagination[limit]=10` ### Response #### Success Response (200) - **data** (array) - An array of article objects. - **meta** (object) - Contains pagination information. - **meta.pagination** (object) - **meta.pagination.start** (integer) - The starting index used for the request. - **meta.pagination.limit** (integer) - The limit used for the request. - **meta.pagination.total** (integer) - The total number of entries available. #### Response Example ```json { "data": [ // ... article objects ], "meta": { "pagination": { "start": 0, "limit": 10, "total": 42 } } } ``` ``` -------------------------------- ### Strapi Plugin Registration and Widget Setup Source: https://docs.strapi.io/cms/admin-panel-customization/homepage The main entry point for the content metrics plugin. It registers the plugin with Strapi, adds a menu link to the admin panel, and registers the 'Content Metrics' widget. It also handles translations and provides a bootstrap function. ```typescript import { PLUGIN_ID } from './pluginId'; import { Initializer } from './components/Initializer'; import { PluginIcon } from './components/PluginIcon'; import { Stethoscope } from '@strapi/icons' export default { register(app) { app.addMenuLink({ to: `plugins/${PLUGIN_ID}`, icon: PluginIcon, intlLabel: { id: `${PLUGIN_ID}.plugin.name`, defaultMessage: PLUGIN_ID, }, Component: async () => { const { App } = await import('./pages/App'); return App; }, }); app.registerPlugin({ id: PLUGIN_ID, initializer: Initializer, isReady: false, name: PLUGIN_ID, }); // Registers the widget app.widgets.register({ icon: Stethoscope, title: { id: `${PLUGIN_ID}.widget.metrics.title`, defaultMessage: 'Content Metrics', }, component: async () => { const component = await import('./components/MetricsWidget'); return component.default; }, id: 'content-metrics', pluginId: PLUGIN_ID, }); }, async registerTrads({ locales }) { return Promise.all( locales.map(async (locale) => { try { const { default: data } = await import(`./translations/${locale}.json`); return { data, locale }; } catch { return { data: {}, locale }; } }) ); }, bootstrap() {}, }; ``` -------------------------------- ### Get All Documents Response (Strapi API) Source: https://docs.strapi.io/cms/api/rest Example response for retrieving multiple documents from the Strapi API. The 'data' field contains an array of document objects, each with an 'id', 'documentId', attributes, and metadata. Pagination information is included in the 'meta' object. ```JSON { "data": [ { "id": 2, "documentId": "hgv1vny5cebq2l3czil1rpb3", "Name": "BMK Paris Bamako", "Description": null, "createdAt": "2024-03-06T13:42:05.098Z", "updatedAt": "2024-03-06T13:42:05.098Z", "publishedAt": "2024-03-06T13:42:05.103Z", "locale": "en" }, { "id": 4, "documentId": "znrlzntu9ei5onjvwfaalu2v", "Name": "Biscotte Restaurant", "Description": [ { "type": "paragraph", "children": [ { "type": "text", "text": "Welcome to Biscotte restaurant! Restaurant Biscotte offers a cuisine based on fresh, quality products, often local, organic when possible, and always produced by passionate producers." } ] } ], "createdAt": "2024-03-06T13:43:30.172Z", "updatedAt": "2024-03-06T13:43:30.172Z", "publishedAt": "2024-03-06T13:43:30.175Z", "locale": "en" } ], "meta": { "pagination": { "page": 1, "pageSize": 25, "pageCount": 1, "total": 2 } } } ``` -------------------------------- ### Get Single Document Response (Strapi API) Source: https://docs.strapi.io/cms/api/rest Example response for retrieving a single document by its 'documentId' from the Strapi API. The 'data' field contains the document object, including its 'id', 'documentId', attributes, and timestamps. An empty 'meta' object is returned if no additional metadata is present. ```JSON { "data": { "id": 6, "documentId": "znrlzntu9ei5onjvwfaalu2v", "Name": "Biscotte Restaurant", "Description": [ { "type": "paragraph", "children": [ { "type": "text", "text": "Welcome to Biscotte restaurant! Restaurant Biscotte offers a cuisine bassics, such as 4 Formaggi or Calzone, and our original creations such as Do Luigi or Nduja." } ] } ], "createdAt": "2024-02-27T10:19:04.953Z", "updatedAt": "2024-03-05T15:52:05.591Z", "publishedAt": "2024-03-05T15:52:05.600Z", "locale": "en" }, "meta": {} } ``` -------------------------------- ### Populate with create() Source: https://docs.strapi.io/cms/api/document-service/populate Demonstrates how to populate relations when creating a new document. ```APIDOC ## POST /api/articles ### Description Creates a new article and populates its associated header image relation. ### Method POST ### Endpoint `/api/articles` ### Parameters #### Request Body - **data** (object) - Required - The data for the new article. - **title** (string) - Required - The title of the article. - **slug** (string) - Required - The slug of the article. - **body** (string) - Required - The body content of the article. - **headerImage** (number) - Required - The ID of the header image to associate. - **populate** (array) - Required - An array of strings specifying the relations to populate. ### Request Example ```javascript strapi.documents("api::article.article").create({ data: { title: "Test Article", slug: "test-article", body: "Test 1", headerImage: 2, }, populate: ["headerImage"], }); ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier of the created article. - **title** (string) - The title of the article. - **slug** (string) - The slug of the article. - **body** (string) - The body content of the article. - **headerImage** (object) - The populated header image object. - **id** (number) - The ID of the header image. - **name** (string) - The name of the header image. #### Response Example ```json { "id": "cjld2cjxh0000qzrmn831i7rn", "title": "Test Article", "slug": "test-article", "body": "Test 1", "headerImage": { "id": 2, "name": "17520.jpg" } } ``` ``` -------------------------------- ### Count Documents with Filters (JavaScript) Source: https://docs.strapi.io/cms/api/document-service Counts documents using the Strapi Document Service API with specified filters. This example demonstrates counting draft documents in English whose names start with 'Pizzeria'. It assumes the 'strapi' object and the 'api::restaurant.restaurant' collection type are accessible. ```javascript /** * 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" } } }) ``` -------------------------------- ### Strapi Setup and Cleanup Functions (JavaScript) Source: https://docs.strapi.io/cms/testing Provides functions to set up and clean up Strapi instances for testing. `setupStrapi` handles user role assignment, and `cleanupStrapi` ensures proper server and database closure, along with temporary file removal. ```javascript async function setupStrapi() { const instance = strapi; const userService = strapi.plugins['users-permissions']?.services?.user; if (userService) { const originalAdd = userService.add.bind(userService); userService.add = async (values) => { const data = { ...values }; if (!data.role) { const defaultRole = await strapi.db .query('plugin::users-permissions.role') .findOne({ where: { type: 'authenticated' } }); if (defaultRole) { data.role = defaultRole.id; } } return originalAdd(data); }; } return instance; } async function cleanupStrapi() { if (!global.strapi) { return; } const dbSettings = strapi.config.get('database.connection'); await strapi.server.httpServer.close(); await strapi.db.connection.destroy(); if (typeof strapi.destroy === 'function') { await strapi.destroy(); } if (dbSettings && dbSettings.connection && dbSettings.connection.filename) { const tmpDbFile = dbSettings.connection.filename; if (fs.existsSync(tmpDbFile)) { fs.unlinkSync(tmpDbFile); } } } module.exports = { setupStrapi, cleanupStrapi }; ``` -------------------------------- ### Filter Restaurants by Name Starting With (GraphQL) Source: https://docs.strapi.io/cms/api/graphql Retrieves restaurants where the 'name' field starts with 'Pizza'. This uses the 'startsWith' operator. ```graphql { restaurants(filters: { name: { startsWith: "Pizza" } }) { name } } ``` -------------------------------- ### Strapi Server Configuration Example (JavaScript) Source: https://docs.strapi.io/cms/configurations/server An example of a Strapi server configuration file (server.js) demonstrating various options like host, port, keys, proxy settings, and cron job configurations. This file allows customization of the Strapi server's behavior. ```javascript module.exports = ({ host: 'localhost', port: 1337, app: { keys: ['myKey1', 'myKey2'], }, // ... other configurations }); ``` -------------------------------- ### Strapi CLI: Start Production Server Source: https://docs.strapi.io/cms/cli Starts the Strapi application with auto-reloading disabled, suitable for production environments. Features requiring application restarts, like the Content-type Builder, are disabled. Environment variables can be used to customize the start. ```bash strapi start ``` -------------------------------- ### Example Strapi Database Migration File (JavaScript) Source: https://docs.strapi.io/cms/database-migrations An example of a Strapi database migration file demonstrating how to use the Knex.js API within the `up()` function. This example shows renaming a table, renaming a column, and updating data. The `up()` function runs within a database transaction. ```javascript module.exports = { async up(knex) { // You have full access to the Knex.js API with an already initialized connection to the database // Example: renaming a table await knex.schema.renameTable('oldName', 'newName'); // Example: renaming a column await knex.schema.table('someTable', table => { table.renameColumn('oldName', 'newName'); }); // Example: updating data await knex.from('someTable').update({ columnName: 'newValue' }).where({ columnName: 'oldValue' }); }, }; ``` -------------------------------- ### Strapi Plugin Development: Plugin Creation and Setup Source: https://context7_llms The Plugin SDK facilitates plugin generation independent of a Strapi project. It includes commands like watch:link and yalc for linking plugins to existing apps, and build/verify commands for packaging. ```bash strapi plugin generate my-plugin yarn strapi develop --watch-admin --watch-plugins yarn strapi build --clean yarn strapi publish ``` -------------------------------- ### GraphQL Pagination by Offset (Start and Limit) Source: https://docs.strapi.io/cms/api/graphql Demonstrates pagination using start and limit parameters in GraphQL. This offset-based approach is useful for fetching a specific range of results. ```graphql { restaurants_connection(pagination: { start: 10, limit: 19 }) { nodes { documentId name } pageInfo { page pageSize pageCount total } } } ``` -------------------------------- ### Strapi Testing Setup Source: https://context7_llms Strapi's testing framework relies on Jest and Supertest with an in-memory SQLite database. It includes helpers for automatic route and role registration, and supports TypeScript configurations. ```javascript // tests/bootstrap.test.js const Strapi = require('@strapi/strapi'); let instance; beforeAll(async () => { instance = await Strapi({ dir: __dirname + '/..', // ... other configurations }); await instance.start(); }); afterAll(async () => { await instance.stop(); }); // Example test using supertest const request = require('supertest')(strapi.server.httpServer); it('should return 200 for /hello route', async () => { const response = await request.get('/hello'); expect(response.status).toBe(200); }); ``` -------------------------------- ### Strapi .env.example File Structure Source: https://docs.strapi.io/cms/configurations/environment This is an example of the .env.example file generated by the Strapi CLI. It outlines the default environment variables for project settings and security keys. These variables serve as placeholders and should be modified in the actual .env file. ```env # Server HOST=0.0.0.0 PORT=1337 # Secrets APP_KEYS="toBeModified1,toBeModified2" API_TOKEN_SALT=tobemodified ADMIN_JWT_SECRET=tobemodified TRANSFER_TOKEN_SALT=tobemodified JWT_SECRET=tobemodified ENCRYPTION_KEY=tobemodified ``` -------------------------------- ### Strapi .env File with Default Settings Source: https://docs.strapi.io/cms/configurations/environment This example shows a typical .env file for a Strapi project, including server, secrets, and database configurations. It demonstrates how to set specific values for host, port, security salts, JWT secrets, and database connection details. ```env # Server HOST=0.0.0.0 PORT=1337 # Secrets APP_KEYS=appkeyvalue1,appkeyvalue2,appkeyvalue3,appkeyvalue4 API_TOKEN_SALT=anapitokensalt ADMIN_JWT_SECRET=youradminjwtsecret TRANSFER_TOKEN_SALT=transfertokensaltvalue JWT_SECRET=yourjwtsecret ENCRYPTION_KEY=yourencryptionkey # Database DATABASE_CLIENT=sqlite DATABASE_HOST= DATABASE_PORT= DATABASE_NAME= DATABASE_USERNAME= DATABASE_PASSWORD= DATABASE_SSL=false DATABASE_FILENAME=.tmp/data.db ``` -------------------------------- ### Install Email Provider using NPM Source: https://docs.strapi.io/cms/features/email Installs the Sendgrid email provider for Strapi using the NPM package manager. This command adds the necessary package to your project's dependencies. ```bash npm install @strapi/provider-email-sendgrid --save ```