# Strife developer documentation Source: https://strife.app/docs Developer documentation for Strife: tutorials to connect your site, how-to guides, and the reference for the SDKs, the CLI, templates, fields and the content index. Strife is a headless CMS: editors work in Strife Studio, and your site reads the content and renders it with your own code. These docs are for the developers who build that site. [How Strife works](https://strife.app/docs/explanation/what-is-strife.md) explains how the parts fit together. **Where to start:** * **Astro:** the [Astro](https://strife.app/docs/tutorials/astro.md) tutorial. `@strifeapp/astro` connects to your team's database, gives you a store to query it, and adds live preview. * **Node.js or Next.js:** [Node.js](https://strife.app/docs/tutorials/getting-started/nodejs.md), then [Next.js](https://strife.app/docs/tutorials/next.js.md). * **.NET:** [.NET](https://strife.app/docs/tutorials/getting-started/dotnet.md). * **AI assistants:** connect the [MCP server](https://strife.app/docs/tools/mcp-server.md) to work with your content, and the [docs MCP server](https://strife.app/docs/how-to-guides/use-the-docs-from-ai-tools.md) to search these docs.
TutorialsStart here! The tutorials will get you started with Strife in no time.getting-started
How-to GuidesStep-by-step guides showing how to achieve common tasks in Strifehow-to-overview.md
ReferenceThe gory details about Strife's SDKs, APIs and configurationreference-overview.md
ExplanationDiscussions and deep dives into key topics of Strifeexplanation-overview.md
--- # Getting started Source: https://strife.app/docs/tutorials/getting-started Connect your site to Strife with the SDK for Node.js or .NET, and query your content in a few steps. To help you get started, we offer two quick start guides tailored to your preferred development environment. If you’re working with JavaScript, check out our **Node.js Getting Started** guide to set up your environment and run your first application. Prefer C#? Our **.NET Getting Started** guide walks you through installation, configuration, and building your first project. **Choose the path that fits your background and start building today:** - [Node.js](https://strife.app/docs/tutorials/getting-started/nodejs.md) - [.NET](https://strife.app/docs/tutorials/getting-started/dotnet.md) --- # Node.js Source: https://strife.app/docs/tutorials/getting-started/nodejs Use Strife from Node.js: install the SDK, create and initialize a store, define a collection, and query your pages and media. ### 1. Install Strife SDK ```bash npm i @strifeapp/strife ravendb ``` ### 2. Create and initialize a Strife store > [!NOTE] > The environment settings were provided during onboarding. ```js import { DocumentStore } from 'ravendb'; const certificate = import.meta.env.STRIFE_CERTIFICATE; let authOptions = { certificate: Buffer.from(certificate, 'base64'), type: 'pfx', password: import.meta.env.STRIFE_CERTIFICATE_PASSWORD, }; const store = new DocumentStore( import.meta.env.STRIFE_DATABASE_URLS.split(','), import.meta.env.STRIFE_DATABASE, authOptions ); export default store.initialize(); ``` ### 3. Define a Collection A [Collection](https://ravendb.net/docs/article-page/7.0/csharp/client-api/faq/what-is-a-collection) is a group of records, called Documents, that all share a common schema. You can define as many Collections as your application needs. Each Document in a Collection is stored in the Database based on the [Fields](https://strife.app/docs/reference/fields.md) that you define, and is automatically queryable using a [Document session](https://ravendb.net/docs/article-page/7.0/nodejs/client-api/session/what-is-a-session-and-how-does-it-work). > [!NOTE] > A Collection in Strife should not confused with a Collection in RavenDB ```json { "collection": "Articles", "fields": [ { "label": "Heading", "editor": { "name": "str-input", "propertyName": "heading", }, } ] } ``` ### 4. Query your pages Using async await syntax: ```js import store from '@/store/index'; const session = store.openSession(); let page = await session .query({ indexName: 'Content/ByUrl' }) q .whereEquals('url', '/about') .firstOrNull(); console.log(`Found page with ${page.heading}`); ``` Or promises: ```js session.query({ collection: "Articles" }) .all() .then((articles) => { if(articles.length) { articles.map(article => console.log(`${article.displayName} was published: ${article.publishedAt}`)); } else { console.log('No articles found'); } }); ``` ### 5. Query your Media Using promises: ```javascript await session.query({ collection: 'Files'}) .whereEquals('mimeType', 'video/mp4') .all() .then(files => { if(files.length) { files.map(file => console.log(`${file.name} with size: ${file.size}`)); } else { console.log('No files found'); } }); ``` ### Search your Content Using promises: ```javascript await session.query({ indexName: "Content/FulltextSearch" }) .search('fields', params.query) .orderByScore() .skip((params.page - 1) * PAGE_SIZE) .take(PAGE_SIZE) .all() .then(hits => { if(hits.length) { hits.map(hit => console.log(`${hit.displayName}`)); } else { console.log('No hits'); } }); ``` ### 6. Setup Real time preview Use in web component by subscribing to the Strife studio's events and call the provided callback function. ```js import { subscribe } from '@strifeapp/strife'; export default class Sections extends LitElement { static properties = { sections: { type: Array }, }; firstUpdated() { // Subscribe to Live Preview events using the`subscribe` function this.unsubscribe = subscribe((data) => { this.sections = data.sections; }); } disconnectedCallback() { super.disconnectedCallback(); this.unsubscribe(); } render() { return repeat(this.sections, (item) => item.id, (item, index) => {…}); } } ``` To have Studio check the page's accessibility and weight in the preview as well, add `` once to the `` of your layout. See [Accessibility and page weight](https://strife.app/docs/how-to-guides/strife-insights.md). --- # .NET Source: https://strife.app/docs/tutorials/getting-started/dotnet Use Strife from .NET: install the SDK, initialize it, define a collection and a template, render content and set up real-time preview. ### 1. Install Strife SDK ```bash dotnet add package strife ``` ### 2. Initialize Strife > [!NOTE] > The environment settings were provided during onboarding. ```json title="appsettings.json" { "DocumentStoreSettings": { "Urls": "", "Database": "", "Certificate": "", "Password": "" }, "Strife": { "Secret": "", "Workspace": "", "StartId": "" } } ``` ```csharp title="Program.cs" using Strife; using Strife.Routing; var builder = WebApplication.CreateBuilder(args); builder.Services.AddStrife(); var app = builder.Build(); app.UseRouting(); app.MapStrife(); app.Run(); ``` ### 3. Define a Collection and Template A [Collection](https://ravendb.net/docs/article-page/7.0/csharp/client-api/faq/what-is-a-collection) is a group of records, called Documents, that all snapshot a common schema. You can define as many Collections as your application needs. Each Document in a Collection is stored in the Database based on the [Fields](https://strife.app/docs/reference/fields.md) that you define, and is automatically queryable using a [Document session](https://ravendb.net/docs/article-page/7.0/nodejs/client-api/session/what-is-a-session-and-how-does-it-work). Use the **Template Builder** in Strife Studio to define Collections and their templates. Then, create a corresponding C# model to represent your Collection in code. > [!NOTE] > A Collection in Strife should not confused with a Collection in RavenDB ```csharp using Strife.Models; public record BlogPost : Content { public string Heading { get; set; } public string Body { get;set; } } ``` ### 4. Rendering Content When using the Strife SDK, content models are automatically resolved and passed to your controller actions without any manual fetching or lookup. Here's a typical example using an `BlogPostController`. ```csharp using Microsoft.AspNetCore.Mvc; using Strife.Binding; public class BlogPostController : Controller { public IActionResult Index([FromContentRoute] BlogPost content) { return View(content); } } ``` #### How It Works * **Automatic Content Binding**:\ By using the `[FromContentRoute]` attribute, Strife automatically resolves and injects the correct `BlogPost` content based on the current route. You don't need to query for the content manually — it's handled for you. * **Model-Driven Views**:\ The resolved `BlogPost` instance is passed directly to the view, making it easy to render content using a strongly typed model. * **Routing Integration**:\ The system maps the incoming route to a specific content item (Document) and ensures that the correct type (e.g., BlogPost) is provided to your action. Here’s a simplified example of how you might use the `BlogPost` model in a Razor view: ```cshtml @model BlogPost

@Model.Heading

@Model.Body
``` By using `[FromContentRoute]`, you can focus on building views and logic without worrying about content retrieval. Strife takes care of resolving the right content based on the route and passing it into your controller actions. ### 5. Setup Real time preview To enable real-time preview and connect your site to **Strife Studio**, include the Strife JavaScript SDK in your project. Add the following to your HTML: ```html ``` Once connected, you can enable **Live Preview** in two ways: * [**Using Strife Web Components**](https://strife.app/docs/reference/live-preview/web-components.md) for quick integration. * [**Building a custom live preview implementation**](https://strife.app/docs/reference/live-preview/custom-live-preview-implementation.md) if you need more control over the preview experience. This setup ensures that content editors can see real-time updates directly on the site as they work in Strife Studio. #### Accessibility and page weight (optional) To have Studio check a page's accessibility and weight in the preview, add the `` element once to the `` of your layout: ```cshtml @RenderBody() ``` See [Accessibility and page weight](https://strife.app/docs/how-to-guides/strife-insights.md) for what editors see. #### Snapshots (optional) Editors can hand a reviewer without a Strife account a **preview link** — `https://example.com/snapshot/{token}` — that shows a frozen, unpublished version of a document on your site for 7 days. Nothing to register: `MapStrife()` resolves the route, your controller receives the snapshot through `[FromContentRoute]` as usual, and `ContextService.GetSnapshot(HttpContext)` tells you when you are rendering one: ```csharp var snapshot = _context.GetSnapshot(HttpContext); // Strife.Services.SnapshotContext, or null if (snapshot != null) { // show a preview notice with snapshot.Name (render as text) and snapshot.ExpiresAt; // skip analytics and Open Graph tags } ``` Expired, revoked or unknown links are your site's ordinary not-found. The route needs a `Content/ByUrl` index built from the `@strifeapp/strife` release that ships snapshots (run `strife push` after updating). Locale handling, the headers the SDK sets, and the CDN/analytics rules are in the [Snapshots](https://strife.app/docs/reference/snapshots.md) reference. ### 6. Querying and Searching To **query** or **search** for documents, use the RavenDB client provided by the SDK. The `IDocumentStore` is available via **dependency injection** in your controllers and services. Here’s an example of querying related documents in a controller: ```csharp using Microsoft.AspNetCore.Mvc; using Strife.Binding; public class BlogListController : Controller { private readonly IDocumentStore _store; public BlogListController(IDocumentStore store) { _store = store; } public IActionResult Index([FromContentRoute] BlogList content) { var viewModel = new BlogListViewModel(content); using (var session = _documentStore.OpenAsyncSession()) { viewModel.CurrentPosts = await session.Query(content.Posts); } return View(viewModel); } }. ``` > [!NOTE] > `content.Posts` is assumed to be a list of BlogPost IDs stored in the `BlogList` document. > > Use `LoadAsync()` when loading specific documents by ID, and `Query()` for broader queries. #### Full-Text Search Example For more advanced search scenarios, such as full-text search with highlighting and scoring, you can query an index like this: ```csharp var hits = await session.Query() .Search(x => x.SearchText, query, @operator: SearchOperator.And) .Highlight(x => x.SearchText, 100, 1, highlightingOptions, out Highlightings highlights) .OrderByScore() .Skip((page - 1) * pageSize) .Take(pageSize) .ProjectInto() .Statistics(out QueryStatistics stats) .ToArrayAsync(); ``` > [!NOTE] > **Note:** A **full-text search index** (e.g., `Content_FullTextSearch`) **must be created manually** in RavenDB. Strife does **not** provide built-in search indexes — this allows you to define custom indexing logic suited to your content. ### Additional Resources For more details on querying, indexing, and advanced search capabilities, see the [RavenDB official documentation](https://ravendb.net/docs/article-page/6.2/csharp/start/getting-started). --- # Use Strife as your Astro CMS Source: https://strife.app/docs/tutorials/astro Use Strife as the CMS for your Astro site: start from the Strife starter or add Strife to your own project, define your content with defineType, deploy it with the CLI, render pages from the content index, and turn on live preview. Strife gives your Astro site a CMS. Editors write and publish in Strife Studio, and your Astro pages read the content on each request and render it with your own components. `@strifeapp/astro` connects your site to your team's database, and live preview shows editors their changes on your site as they type. There are two ways to start: * [Start from the Strife starter](#start-from-the-strife-starter), an Astro site that is set up and has a first page. * [Add Strife to your own Astro project](#add-strife-to-your-own-astro-project). You need Node.js 22.12 or later and Astro 5, 6 or 7. If you are new to Strife, [How Strife works](https://strife.app/docs/explanation/what-is-strife.md) explains the parts. ## Start from the Strife starter Run this where you want the new project: ```bash npm create @strife ``` The CLI signs you in through your browser, and lets you pick a team or create a new one. It then sets up the starter, writes the connection secret to `.env`, deploys the starter's schema and adds a first page. Start the site: ```bash npm run dev ``` Open the address Astro prints, usually `http://localhost:4321`. The page shows its heading and body from Strife. Open the page in Studio, where the CLI printed a link, and edit it to watch your site change as you type. The starter is a working example of everything below: * the schema is in `schemas/home.ts` * the query is in `src/pages/index.astro` * live preview is in `src/components/HomeContent.svelte` ## Add Strife to your own Astro project ### 1. Install the packages ```bash npx astro add @strifeapp/astro npm install @strifeapp/strife npm install --save-dev @strifeapp/cli ``` * `astro add` installs the integration and adds it to `astro.config.mjs`. * `@strifeapp/strife` has live preview and the schema tools. * `@strifeapp/cli` gives you the `strife` command. ### 2. Connect the project to your team From your project's folder, run: ```bash npx strife . ``` The CLI signs you in, links the folder to a team (or creates one), and writes `STRIFE_SECRET` to `.env`. It also adds `.env` to `.gitignore`. The secret contains your certificate's private key, so keep it out of version control and out of the browser. See [How your site connects](https://strife.app/docs/explanation/ravendb.md#how-your-site-connects). ### 3. Configure Astro ```js // astro.config.mjs import { defineConfig } from 'astro/config'; import strife from '@strifeapp/astro'; export default defineConfig({ // Live preview needs pages rendered on request. output: 'server', // The address Studio previews a new team's site on. server: { port: 4321 }, integrations: [strife()], }); ``` `astro add` adds the integration but not `output: 'server'`, so add it yourself. Live preview reads a preview token on each request, and that only happens for pages rendered on request. A team the CLI creates previews `http://localhost:4321`, so keep the dev server on that port. An existing team previews the site address in its settings. Then declare the types that `@strifeapp/astro` doesn't ship yet, in `src/env.d.ts`: ```ts /// declare module 'strife:store' { import type { DocumentStore } from 'ravendb'; export const store: DocumentStore; } declare namespace App { interface Locals { editMode?: boolean; } } ``` ### 4. Define your content Write a schema for each kind of page. Create `schemas/article.ts`: ```ts import { defineType, fields } from '@strifeapp/strife/schema'; export const article = defineType({ name: 'article', title: 'Article', type: 'document', fields: { heading: fields.text({ label: 'Heading', localizable: true }), body: fields.html({ label: 'Body', localizable: true }), }, }); ``` Point the CLI at your schemas in `strife.config.ts`: ```ts import { defineConfig, glob } from '@strifeapp/strife/schema'; export default defineConfig({ schema: glob('./schemas/**/*.ts'), }); ``` Deploy them, and generate types for them: ```bash npx strife push npx strife typegen generate ``` * `strife push` creates the Article template in your team and deploys `Content/ByUrl`, the content index your pages query. Run it again whenever you change a schema. * `strife typegen generate` writes an interface for each template to `.strife/types.ts`, such as `Article extends Content`. [Schemas](https://strife.app/docs/reference/cli/schemas.md) and the [Field Reference](https://strife.app/docs/reference/field-reference.md) list everything you can define. ### 5. Write a page in Studio Open Studio, create an Article, give it an address and publish it. See [Your first page](https://strife.app/docs/user-guide/getting-the-basics) in the user guide. ### 6. Render pages Create `src/pages/[...slug].astro`. It finds the page for the address being visited and renders it: ```astro --- import { store } from 'strife:store'; import LivePreview from '@strifeapp/astro/LivePreview.astro'; import type { Article } from '../../.strife/types'; const session = store.openSession(); const find = (status: string) => session .query
({ indexName: 'Content/ByUrl' }) .whereEquals('url', Astro.url.pathname) .whereEquals('locale', 'en') .whereEquals('status', status) .selectFields(['displayName', 'heading', 'body']) .noCaching() .firstOrNull(); // Visitors see the published version. In Strife's live preview, show the // pending edits first, then a page that was never published. const page = Astro.locals.editMode ? ((await find('draft')) ?? (await find('unpublished')) ?? (await find('published'))) : await find('published'); if (!page) { return new Response(null, { status: 404 }); } --- {page.displayName}

{page.heading}

``` * `Content/ByUrl` has a row for each page and language. A page's pending edits and scheduled publish are rows too, at the same address, so the query always filters on `status`. * Visitors get the `published` row. * In live preview, `Astro.locals.editMode` is `true`. The page then shows the pending edits (`draft`), or a page that was never published (`unpublished`). * [Index URL](https://strife.app/docs/reference/database/index-url.md) describes every kind of row. * `selectFields` returns each field in the row's language. Without it, the query returns the whole document, where a translated field is an object such as `{ en: '…' }`. * `.noCaching()` stops the RavenDB client from caching a response for every address someone tries, which matters in a catch-all route. * `set:html` renders the rich text body's HTML. Start the dev server with `npm run dev` and open the page's address. ### 7. Turn on live preview `` loads Strife's live preview script when your page is open in Studio, and does nothing for visitors. Place it once, in the `` of your layout. To have Studio check the page's accessibility and weight in the preview as well, add `` once to your layout's ``. See [Accessibility and page weight](https://strife.app/docs/how-to-guides/strife-insights.md). To update the page while editors type, read the live document in a client component with `subscribe` from `@strifeapp/strife`. It calls your function with the document on every change. A translated field can arrive as text or as an object keyed by language. Here is a Svelte component. It needs Astro's Svelte integration (`npx astro add svelte`), listed before `strife()` in `integrations` as in the starter: ```svelte

{heading}

{@html body}
``` Render it from your page with ``. The same pattern works in React or Vue: call `subscribe` when the component mounts, and return its result to stop listening. See [Live preview](https://strife.app/docs/reference/live-preview.md) for the details. ## Deploy `astro dev` works without more setup. For production builds, add the Astro adapter for your host: | Deploy target | Adapter | Install | | --- | --- | --- | | Self-hosted Node.js | `@astrojs/node` | `npx astro add node` | | Vercel | `@astrojs/vercel` | `npx astro add vercel` | | Netlify | `@astrojs/netlify` | `npx astro add netlify` | | Cloudflare Workers | `@astrojs/cloudflare` | `npx astro add cloudflare` | Then set `STRIFE_SECRET` as a server-side secret in your host's environment settings. `@strifeapp/astro` reads it on the server when a page is requested, and never builds it into your site's files. The certificate makes the value long, and some hosts limit how long a variable can be: the [`@strifeapp/astro` README](https://www.npmjs.com/package/@strifeapp/astro) lists the limits. ## More for your site * **Snapshots:** let editors share a link to a frozen copy of a page for review. See [Snapshots](https://strife.app/docs/reference/snapshots.md). * **Open in Strife:** a toolbar that takes editors from a page on your site to the same page in Studio. See [Open in Strife](https://strife.app/docs/how-to-guides/open-in-strife-toolbar.md). * **Accessibility and page weight:** place `` in your layout's body and Studio checks each page's accessibility and weight in the live preview. On teams with Content Insights, the results also go to Insights. See [Accessibility and page weight](https://strife.app/docs/how-to-guides/strife-insights.md). --- # Quickstart Source: https://strife.app/docs/tutorials/quickstart Easy as 1, 2, 3! --- # Next.js Source: https://strife.app/docs/tutorials/next.js Build an application using Next.JS and Strife ### Prerequisites > [!WARNING] > Before you read any further, make sure that you have a valid invite and received the welcome email. Before you begin, ensure you have the following: * A package manager (NPM) * A [Next.js](https://nextjs.org/docs/getting-started/installation) app ### Installation First, install the RavenDB Node.js client using NPM: ```bash title=">_ Terminal" npm install ravendb --save ``` ### Configuration Add your RavenDB database configuration to the `.env.local` file in your Next.js app: > [!NOTE] > You may need to create `.env.local` if it does not exist. ```sh title=".env.local" STRIFE_CERTIFICATE=xxx STRIFE_CERTIFICATE_PASSWORD=xxx STRIFE_DATABASE_URLS=xxx STRIFE_DATABASE=xxx ``` ### Create your first query To request the home page based on the URL, create a query using the RavenDB Node.js client: > [!NOTE] > This query uses a predefined index called `Content/ByUrl`. The index is used to query content based on a relative URL. ```javascript title="src/app/page.js" import { DocumentStore } from 'ravendb'; const certificate = process.env.STRIFE_CERTIFICATE; const authOptions = { certificate: Buffer.from(certificate, 'base64'), type: 'pfx', password: process.env.STRIFE_CERTIFICATE_PASSWORD, }; const store = new DocumentStore( process.env.STRIFE_DATABASE_URLS.split(', '), process.env.STRIFE_DATABASE, authOptions ); store.initialize(); const session = store.openSession(); const query = session .query({ indexName: 'Content/ByUrl' }) .whereEquals('url', '/'); const home = await query.firstOrNull(); ``` ### Real-Time Preview #### Prepare the App for Real-Time Updates Include the Strife JavaScript SDK using the [Script Component](https://nextjs.org/docs/pages/api-reference/components/script) in your Next.js app just before the end of the `` tag in your `src/app/layout.js` file: ```javascript title="src/app/layout.js" import Script from 'next/script' // ... ``` | Attribute | Required | Meaning | | ------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `team` | no | The team id. Without it, Strife resolves the team from the page's host among the editor's own teams. Pass it to skip the host lookup; together with `document-id` the host need not be registered at all. | | `document-id` | no | The Strife content document id of the page, the one Studio shows in the editor URL. In `Content/ByUrl*` index rows that is usually the `docId` field, not the row's own `id`. Preferred: Strife opens exactly that document, which also covers virtual sub-pages. Without it, Strife resolves the page URL through the content index. | | `api` | no | The Strife API origin. Defaults to `https://api.strife.app`. | | `lang` | no | Language of the toolbar's labels. Defaults to the page's ``: Swedish for `sv`, English for everything else. | The element renders only when the cookie is present, the page is top-level (not framed) and the URL does not carry `?token=`. Collapsed it is a small tab on the right edge with the Strife mark; hovering, focusing or tapping it unfolds two icon actions with tooltips, **edit in Strife** and **hide**. The tooltips use native Interest Invokers (`interestfor` + `popover="hint"`) in Chrome and Edge 142+, and a built-in fallback elsewhere. Style it from outside with `strife-toolbar::part(island)`, `::part(mark)`, `::part(edit)`, `::part(hide)` and `::part(tooltip)`, or move it with a rule on `strife-toolbar` itself (it is `position: fixed`, vertically centred on the right edge by default). ## Load the module only for connected browsers (optional) The element renders only in connected browsers, but the import above downloads and runs the module on every page view, for every visitor and crawler. To keep it off ordinary page views, import it only when the toolbar can matter: when another window opened the page (the play button's handshake), or when the browser already has the cookie. ```astro --- // src/layouts/Layout.astro const { pageData } = Astro.locals; --- ``` Your bundler puts the module in a file of its own that only those browsers fetch. Keep both conditions: without `window.opener`, the first visit from the play button never loads the module, so the cookie is never set. Studio waits for the page to answer, so a module that loads a moment later still connects. ## Cookies and consent `strife-toolbar` is a first-party, host-only cookie holding the value `1`, set by the toolbar script after the editor arrived from Strife. Classify it as a necessary/functional cookie in your consent tool. ## Limitations * The handshake is not signed. Any page that opens your site with `window.open` can make the toolbar appear in that browser; the button only leads to Strife's login, so nothing is exposed. * Safari caps script-set cookies to seven days of Safari use without a visit to the site. An editor who browses the site weekly keeps the connection; otherwise she opens the page from Studio again. * On a multi-language site, Studio does not necessarily open the document in the locale of the page. ## Troubleshooting * **The toolbar never appears after opening the page from Studio**: the page must be top-level (not framed), the address must not carry `?token=`, and the tab must still know its opener. A site that sends `Cross-Origin-Opener-Policy` (`same-origin` or `same-origin-allow-popups`), or a script that clears `window.opener` before the toolbar module runs, severs the connection; so does closing the Studio tab before the page has loaded. After a play, `document.cookie` should contain `strife-toolbar=1`. * **Clicking lands on the content list instead of the document**: pass `document-id`, or register the host the site is served on for the team. * **`None of your teams is registered for …`**: the editor is not a member of a team that has this host registered. Register the host, or pass `team` together with `document-id`. --- # Accessibility and page weight: the strife-insights element Source: https://strife.app/docs/how-to-guides/strife-insights Turn on Studio's accessibility audit and page-weight check with the strife-insights element: the results in the live preview for every editor, and in Insights and the content list on teams with Content Insights. Where to place it in Astro, Next.js, Vue and Nuxt, .NET and plain HTML, and troubleshooting. The `` element lets Studio check your site's pages: an accessibility audit, and what each page weighs. The checks run while an editor has a page open in Studio's live preview, and the results go to two places: * **The live preview**, for every editor: the preview's toolbar shows them while the editor works. * **Insights and the content list**, on teams with Content Insights: Studio stores the results, so the accessibility audit shows in [Insights](https://strife.app/docs/user-guide/improving-content/insights), and both checks can be filtered on in the content list. Your site turns both checks on with the one element, placed once in your layout's body: ```html ``` The element renders nothing and needs no script of its own. Leave it out and neither check runs, so Insights gets no accessibility data either. ## How it works * **The checks run in your page, and only in the preview.** The preview SDK (`@strifeapp/strife`) defines the element only when the page is framed, as it is in Studio's preview, so your visitors get an empty tag. It runs the accessibility audit with [axe-core](https://github.com/dequelabs/axe-core), which it downloads only when Studio asks for an audit, so visitors never load it. It weighs the page's images and embeds from the browser's own measurements. * **Only Studio's new interface shows them.** It asks for the audit when it connects to the page. The legacy interface never asks, and shows neither check. * **Only on the page the editor opened.** If your site's client-side router swaps in another page inside the preview, the checks don't run there: that page's result would be shown, and stored, as the page being edited. * **The page sends nothing anywhere itself.** It hands the results to Studio. On teams with Content Insights, Studio stores them per page and language, for Insights and the content list's Accessibility and Performance filters. The data comes from editing, not from your visitors. ## Requirements * **`@strifeapp/strife` 1.23.0 or later** on the page. A site that loads it from a CDN without a version, such as `https://unpkg.com/@strifeapp/strife`, already runs the latest. With npm, update it: `npm install @strifeapp/strife@latest`. * **On Astro, `@strifeapp/astro` 1.10.0 or later.** See the Astro tab below. * **Studio's new interface** for the editor. * **Content Insights on the team**, to store the results. Without it, editors still see them in the preview. ## Add the element Put the element in the layout every page uses, inside ``. Never put it in ``: the browser ends the head at an element it doesn't know and moves everything after it into the body. `hidden` keeps the empty element out of your layout (in a grid or flex body it would take a track and a gap); the SDK still finds it. A layout rendered on the client, or inside a shadow root, works too: the checks start when the element connects. **Astro** ```astro title="src/layouts/Layout.astro" --- import LivePreview from '@strifeapp/astro/LivePreview.astro'; --- ``` `` loads the preview SDK only in Studio's preview. Use `@strifeapp/astro` 1.10.0 or later, and if your `package.json` lists `@strifeapp/strife` as well, raise it to 1.23.0 or later too. If the layout has ``, remove it (see [Coming from the Insights component](#coming-from-the-insights-component)). **Next.js** ```tsx title="src/app/layout.tsx" import type { ReactNode } from 'react'; export default function RootLayout({ children }: { children: ReactNode }) { return ( {children} ); } ``` Load the preview SDK as in the [Next.js tutorial](https://strife.app/docs/tutorials/next.js.md). It loads the SDK on every page, so read [Security](#security) below. TypeScript doesn't know the tag and reports `Property 'strife-insights' does not exist on type 'JSX.IntrinsicElements'`. Declare it once, in a file your `tsconfig.json` includes: ```ts title="strife-elements.d.ts" import type { DetailedHTMLProps, HTMLAttributes } from 'react'; declare module 'react' { namespace JSX { interface IntrinsicElements { 'strife-insights': DetailedHTMLProps, HTMLElement>; } } } ``` Keep the `import` line: without it, the file replaces React's types instead of adding to them. This works with the types for React 18 and 19. In JavaScript you need none of it. **Vue and Nuxt** Put the element in the component every page renders in, such as `app.vue` in Nuxt or `App.vue` in Vue: ```vue title="app.vue" ``` Vue first tries to resolve the tag as a component and warns `Failed to resolve component: strife-insights`. Tell its compiler that the tag is a custom element: ```ts title="nuxt.config.ts" export default defineNuxtConfig({ vue: { compilerOptions: { isCustomElement: (tag) => tag.startsWith('strife-'), }, }, }); ``` With Vue and Vite, the same option goes to the Vue plugin in `vite.config.ts`: `vue({ template: { compilerOptions: { isCustomElement: (tag) => tag.startsWith('strife-') } } })`. **.NET** ```cshtml title="Views/Shared/_Layout.cshtml" @RenderBody() ``` The layout loads the preview SDK as in [Setup Real time preview](https://strife.app/docs/tutorials/getting-started/dotnet.md#5-setup-real-time-preview) in the .NET tutorial. **HTML** ```html … ``` An address without a version always loads the latest SDK. In any other framework the element is plain HTML. If its compiler rejects elements it doesn't know, tell it that `strife-insights` is a custom element: in Angular, add `CUSTOM_ELEMENTS_SCHEMA` to the component's `schemas`. ## Coming from the Insights component In `@strifeapp/astro` 1.9, `` in the head ran the accessibility audit. From 1.10.0 it renders nothing, and the SDK runs the audit itself from 1.23.0. An Astro site that still has `` from `@strifeapp/astro` 1.9.0 or earlier gets neither check once it picks up `@strifeapp/strife` 1.23.0. Update `@strifeapp/astro` to 1.10.0 or later, remove `` and add the element. ## Security The element is not a security boundary: the SDK runs the checks for whatever page frames it and asks, and the audit's result includes short HTML excerpts of the page. If your site loads the SDK for every visitor and renders anything visitor-specific, load it only on preview requests (as `` does on Astro), or limit who may frame your pages with `Content-Security-Policy: frame-ancestors`. ## What editors see * **Accessibility:** a button in the preview's toolbar with the number of failing rules. It lists every rule by impact, with the failing elements: hovering one outlines it in the preview, and clicking one opens the field it renders. The audit runs once the page has connected, 1.5 s after the editor's last edit, and on the rerun button. * **Page weight:** the page's level (Poor, Needs improvement or Great) in its own tool, with the findings split into **Your content** and **Template and code**. Only content findings set the level. * **Stored results**, on teams with Content Insights: the accessibility audit in [Insights](https://strife.app/docs/user-guide/improving-content/insights), and both checks as the content list's **Accessibility** and **Performance** filters. A page edited since its last check shows as unchecked until it is opened in the preview again. [Live preview](https://strife.app/docs/reference/live-preview.md#accessibility-in-the-preview) has the details of both checks: how a finding is tied to a field, what the page-weight check measures and where the sizes come from. ## Troubleshooting * **No accessibility or page-weight button in the preview:** * Check that `` is in the `` of the page in the preview frame. Your browser's developer tools show the frame's elements. * Check the SDK's version: `npm ls @strifeapp/strife` lists the installed versions, and the page needs 1.23.0 or later. * On Astro, check that `@strifeapp/astro` is 1.10.0 or later. * Check that the editor uses Studio's new interface. * **Vue or Nuxt warns `Failed to resolve component: strife-insights`:** set `isCustomElement` as in the Vue and Nuxt tab. * **TypeScript reports `Property 'strife-insights' does not exist on type 'JSX.IntrinsicElements'`:** add the declaration from the Next.js tab. * **The results show in the preview, but not in Insights or the content list's filters:** the team doesn't have Content Insights. * **Insights says "No accessibility data yet for this page":** the page hasn't been checked yet. Open it in the live preview once, after the element is in place. * **Image sizes marked ≈:** the image comes from another origin without a `Timing-Allow-Origin` header, so its size is estimated. See [Performance in the preview](https://strife.app/docs/reference/live-preview.md#performance-in-the-preview). --- # Responsive images Source: https://strife.app/docs/how-to-guides/responsive-images Serve each visitor an image file that fits their screen: add widths to fields.image(), write srcset from the value and describe your layout with sizes. Patterns for heroes, content images, card grids and fixed-size images. A responsive image gives the browser the same picture in several widths and lets it pick the one that fits the visitor's screen. A phone then downloads a phone-sized file, not the desktop one, and a high-density screen still gets a sharp image. The work is split in two: * **Strife writes `srcset`.** A field with `widths` gets a list of candidates — the same crop in several widths — whenever an editor saves the image. * **Your site writes `sizes`.** Only your layout knows how wide the image is on the page. On lazy-loaded images you can let the browser measure it instead. The browser does the rest: it weighs the rendered width, the screen's pixel density and things like a data-saver setting, and picks a candidate. `srcset` and `sizes` describe; they don't instruct. ## 1. Add widths to the field ```ts fields.image({ label: 'Image', width: 1344, height: 896, format: 'avif', widths: 'auto', }) ``` * **`width`** is the largest candidate. Set it to the largest width the image is shown at, in CSS pixels, times two — 1344 for an image that is at most 672px wide. The browser never gets a larger file than this. * **`widths: 'auto'`** gives about 25 % steps from 320px up to `width`. Use an array (`widths: [400, 800, 1344]`) when you know your layout's widths. * The field's crop is the same in every candidate; only the size changes. From the next time an editor picks or crops an image in that field, in either of Strife Studio's interfaces, its value has a `source.srcset`: ```json { "width": 1344, "height": 896, "alt": "A lake below wooded mountains", "source": { "url": "https://cdn.strife.app/…/w:1344/…", "srcset": "https://cdn.strife.app/…/w:320/… 320w, https://cdn.strife.app/…/w:400/… 400w, …, https://cdn.strife.app/…/w:1344/… 1344w", "placeholder": "#4d6a6f" } } ``` > [!NOTE] > `source.srcset` is absent on images saved before you added `widths`, on SVG and GIF images (vector graphics scale on their own, and an animated GIF would be rendered once per width), on images written through the API rather than in Strife Studio, and, in Studio's classic interface, on images smaller than the field's size. Your markup keeps working: the browser uses `src`. ## 2. Write the markup Every pattern below uses the same three things: `srcset` from the value, a `sizes` that describes your layout, and `width`/`height` so the browser can reserve the space before the image arrives. ```css img { max-inline-size: 100%; block-size: auto; } ``` ### Full-width hero The page's largest image at the top, usually its Largest Contentful Paint (LCP) element. It spans the viewport, so `sizes="100vw"`. ```astro {hero.alt} ``` * Never put `loading="lazy"` on the LCP image, and use `fetchpriority="high"` on one or two images at most. * The image is in the HTML from the server, so the browser finds it right away; you don't need a ``. * For a 3:2 hero shown up to about 1440 CSS pixels wide, `width: 2880, height: 1920`. To keep a hero from growing too tall on wide screens, cap its height with CSS. The box is then wider than the image, so the image still scales with the width and `sizes` is still right; only a little height is cropped. ```css .hero { inline-size: 100%; aspect-ratio: 3 / 2; max-block-size: min(100dvh - 4rem, 1000px); overflow: hidden; } .hero img { inline-size: 100%; block-size: 100%; object-fit: cover; } ``` > [!WARNING] > Give the box a definite width (`inline-size: 100%`). With `width: auto`, `aspect-ratio` turns the height cap into a width cap and the box shrinks instead of cropping. ### Content image An image in a text column, further down the page. It loads lazily, so `sizes` can start with `auto`: the browser measures the image's width when it is about to load. Browsers that don't support `auto` yet read the rest of the list, so describe the column after the comma. ```astro {image.alt} ``` The same value can appear in several places with a different `sizes` in each; the field's `width` only caps the largest candidate. ### Card grid Many images in a grid that changes its number of columns. Describe one card's width per breakpoint. The cards below the fold load lazily with `auto`: ```astro {card.alt} ``` The first row is probably visible when the page loads, and an image in the viewport should not be lazy-loaded. Leave out `loading="lazy"` there, and with it `auto`: ```astro {card.alt} ``` > [!WARNING] > Use `sizes="auto"` only together with `loading="lazy"`. On an image that isn't lazy-loaded, browsers treat it as a 300×150 box and ignore the rest of the list. ### Fixed size Avatars, logos and thumbnails are always the same size in CSS; only the screen's pixel density changes. Two candidates — 1x and 2x — are enough, and `sizes` is just the image's width: ```ts fields.image({ label: 'Avatar', width: 192, height: 192, format: 'avif', widths: [96, 192] }) ``` ```astro {avatar.alt} ``` The same value works at another size with another `sizes`, for example `sizes="48px"` in a list. ## 3. A complete example The patterns above differ only in `sizes` and in whether the image is lazy-loaded. A small component keeps the rest in one place: an image without a value renders nothing, an image without `source.srcset` falls back to `src`, `sizes="auto"` is used only on lazy images, and the placeholder colour fills the space while the file loads. ```astro title="src/components/StrifeImage.astro" --- import type { Image } from '@strifeapp/types'; interface Props { image: Image | null | undefined; /** How wide the image is in your layout, e.g. "100vw" or "(min-width: 64rem) 33vw, 100vw". */ sizes: string; /** The page's main image (its LCP element): loaded at once, at high priority. */ priority?: boolean; class?: string; } const { image, sizes, priority = false, class: className } = Astro.props; const source = image?.source; const srcset = source?.srcset || undefined; --- {image && source?.url && ( {image.alt )} ``` Use it with the field from step 1 and a `sizes` per place in your layout: ```ts title="schemas/home.ts" import { defineType, fields } from '@strifeapp/schema'; export const home = defineType({ name: 'home', title: 'Home', fields: { heading: fields.text({ label: 'Heading', localizable: true }), // A full-width hero, at most 1600 CSS pixels wide: 3200 for 2x screens. hero: fields.image({ label: 'Hero', width: 3200, height: 1350, format: 'avif', widths: 'auto' }), }, }); ``` ```astro title="src/pages/index.astro" --- import StrifeImage from '../components/StrifeImage.astro'; const page = await getPage('/'); // however your site loads the document --- ``` The hero then reaches the browser like this (URLs shortened): ```html A skater mid-air above a concrete ramp ``` `width` and `height` are the field's size: they only give the aspect ratio, so the browser reserves the right space before the file arrives and nothing jumps. In this example the original is 1672 pixels wide, so the largest candidate is 1672w, not 3200w: Strife never makes a candidate wider than the original. ### Check what the browser picked Open the page with DevTools' device toolbar, select the image in the **Elements** panel and read `currentSrc` in the **Properties** pane (or filter the **Network** panel by **Img**). The `w:` in the URL is the candidate's width. For the hero above, a 390-pixel phone at 3x needs 1170 pixels and gets the 1216w candidate, and a 768-pixel tablet at 2x needs 1536 and gets 1672w, the largest there is. Reload after each change of screen size: a browser that already has a larger candidate in its cache may keep using it. > [!NOTE] > A change to `width`, `height` or `widths` in your schema reaches each image the next time an editor picks or crops it; until then the image keeps the candidates it was saved with. To get large candidates, upload originals at least as wide as the field's `width`. ### Live preview While an editor zooms or pans an image in Strife Studio, the preview receives a temporary picture in `source.url` and no `source.srcset`; the candidates follow when the editor lets go. If your page updates images live (through `subscribe`, see [Custom Live Preview implementation](https://strife.app/docs/reference/live-preview/custom-live-preview-implementation.md)), remove `srcset` and `sizes` when the value has none. Otherwise the browser keeps showing the old candidates instead of the new picture: ```js img.src = image.source.url; if (image.source.srcset) { img.srcset = image.source.srcset; img.sizes = sizes; } else { img.removeAttribute('srcset'); img.removeAttribute('sizes'); } ``` ## Placeholder `source.placeholder` is the image's average color. Use it as a background so the reserved space isn't empty while the image loads: ```astro ``` ## When the shape has to change Everything here is the same crop in different sizes. When a design needs a different crop per screen — a tall image on phones and a wide one on desktop — that is art direction, done with `` and a `` per shape. Cropping a wide image with CSS to fill a tall phone screen makes the phone download pixels it never shows. ## Further reading * [Learn Images: Descriptive syntaxes](https://web.dev/learn/images/descriptive) — `srcset`, `sizes` and how the browser chooses * [Learn Images: Prescriptive syntaxes](https://web.dev/learn/images/prescriptive) — `` and art direction * [Optimize Largest Contentful Paint](https://web.dev/articles/optimize-lcp) — the LCP image * [Browser-level image lazy loading](https://web.dev/articles/browser-level-image-lazy-loading) * [MDN: Using responsive images in HTML](https://developer.mozilla.org/en-US/docs/Web/HTML/Guides/Responsive_images) * [MDN: `sizes`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/sizes), including `auto` --- # Snapshots on an Astro site that queries the index Source: https://strife.app/docs/how-to-guides/snapshots-astro-without-the-sdk Serve snapshots from an Astro site that queries the Content/ByUrl index itself, without the SDK's snapshot middleware or a dedicated snapshot route. If your Astro site resolves pages by querying `Content/ByUrl` directly — a middleware that looks the current URL up in the index and puts the row on `Astro.locals` — you do not need the SDK's snapshot middleware, the `snapshot/[token].astro` page, or any new route to serve snapshots. A snapshot's rows carry the snapshot path as their `url`, so the lookup you already have resolves them. **The integration is one clause in one query, plus three projected fields.** This guide is the worked version of the contract in [Snapshots → Serving snapshots without the SDK](https://strife.app/docs/reference/snapshots.md#serving-snapshots-without-the-sdk). Read that section for the rules; read this one for the code. > [!NOTE] > **Vocabulary.** Editors see these as **snapshots** in Strife. The mechanism keeps the name `snapshot` everywhere you touch it — the `/snapshot/{token}` path, `status: "snapshot"`, `snapshotToken`, `snapshotName`. Same thing, two audiences. ## Before you start * **Deploy the index.** Run [`strife push`](https://strife.app/docs/reference/cli/commands.md#strife-push) from a `@strifeapp/strife` release that ships snapshots. Until that has happened, Strife refuses to create a snapshot at all, so nothing can reach your site. * **Render on demand.** Snapshot paths must not be prerendered, statically generated, or cached at the edge. On a site with `output: "server"` this is already true; on a hybrid site, make sure the route that resolves pages is `prerender = false`. * **You do not need `@strifeapp/astro` upgraded.** This path uses no SDK snapshot API. A site pinned to a pre-snapshot version of the package works exactly the same. ## 1. Admit `status == "snapshot"` — in the by-URL lookup only Your visibility predicate today is some form of "published, plus the legacy null-status fallback". Snapshot rows carry `status: "snapshot"` and `draft: true`, so nothing you have matches them. Add the one branch, and add it **only** to the query that resolves the current page by exact URL: ```typescript // src/data/contentIndex.ts export function visibleByUrlQuery( session: IDocumentSession, locale: string, url: string, editMode: boolean, ): IDocumentQuery { if (editMode) { return visibleContentQuery(session, locale, editMode).whereEquals("url", url); } // A snapshot's rows carry the snapshot URL itself ("{root-slug}/snapshot/{token}"), // so admitting status = "snapshot" here is the whole integration. Exact-URL lookups // ONLY — listings stay published-only, or they would enumerate secret snapshot tokens. return session .query({ indexName: CONTENT_INDEX }) .whereEquals("locale", locale) .andAlso() .openSubclause() .whereEquals("status", "published") .orElse() .whereEquals("status", "snapshot") .orElse() .openSubclause() .whereEquals("status", null) .andAlso() .whereEquals("draft", false) .closeSubclause() .closeSubclause() .andAlso() .whereEquals("url", url); } ``` Three things about that query are load-bearing: * **The locale clause.** Snapshot `url`s coincide across languages whenever the site's root slug does not vary by locale, and your code cannot tell which case it is in. Always pair `url` with the resolved locale. A site on this path resolves the **exact** locale only — there is no `snapshotLocale` fallback here, so a reviewer who switches to a language the snapshot never had gets your ordinary not-found. * **The url clause stays outside the visibility subclause.** Keep the OR-branches wrapped so the caller's `url` binds with AND. A stray `orElse` at the top level turns "published *or* snapshot, at this URL" into "published, *or* anything shared anywhere". * **Listings keep the old predicate.** Collection queries, sitemaps, hreflang alternates and search all stay published-only. A listing that admits snapshot rows publishes the secret tokens. ## 2. Project the three fields you will read The snapshot fields are stored in the index, so they come back through `selectFields`. Add them where you project the current page's row: ```typescript // src/middlewares/loadRouteData.ts async function findPageDataByPath(session, locale, pathname, editMode) { return await visibleByUrlQuery(session, locale, pathname, editMode) .selectFields([ "id", "displayName", "url", "collection", "status", // "snapshot" tells the rest of the site what it is looking at "snapshotName", // the editor's label, for an optional banner "expiresAt", // UTC round-trip string, for an optional banner "publishedDate", // …your existing fields ]) .firstOrNull(); } ``` `collection` comes back exactly as it does for the published document, so your view mapping picks the same layout and components it always would. That is the point of this approach: a snapshot is not a special kind of page, it is the same page with unpublished content. ## 3. Let your published-check pass a snapshot row Most sites of this shape have a guard that 404s anything without a publish date. A snapshot deliberately has none: ```typescript // src/middlewares/checkPublished.ts const isPublished = pageData && !pageData.deleted && // A snapshot renders a frozen, unpublished snapshot on purpose; its row only // exists while the snapshot is active (expiry soft-deletes it). (pageData.status === "snapshot" || (pageData.publishedDate && new Date(pageData.publishedDate) < new Date())); ``` **You do not need an expiry check.** Expiry and revocation work by the rows disappearing: Strife soft-deletes the snapshot, and the index drops its rows — normally within about a minute of the instant, and at the next worker start if an alarm was missed. `expiresAt` is on the row if you want to show it, or to add a stricter check of your own. ## 4. Optional: tell the reviewer what they are looking at Nothing above renders a banner, and the page works without one. If you want it, the row carries what you need: ```astro --- // src/layouts/Layout.astro const page = Astro.locals.pageData; --- {page?.status === "snapshot" && ( )} ``` Render `snapshotName` as **text only**, never `set:html`. It is editor-typed input. ## 5. Own the hygiene the SDK would have set This is the part a raw integration inherits, and the part worth reviewing before you ship. On snapshot responses: | What | Why | | --- | --- | | `X-Robots-Tag: noindex, nofollow` | The URL is a secret; keep it out of search indexes. | | `Cache-Control: private, no-store`, and no CDN rule that overrides it | A cached lookup serves a revoked link until the cache expires. | | `Referrer-Policy: no-referrer` | Otherwise the token leaks in the `Referer` of everything the page links to. | | No Open Graph or social tags | A link preview would fetch and cache the page somewhere else. | | No analytics beacon | A snapshot is not audience traffic, and the beacon carries the path — that is the token. | | Your own edit/preview affordances stay off | A valid editor token in the request must not switch on draft branching or a live-preview client on a snapshot path. | The last row is the one that bites. If your site imports a live-preview client unconditionally, the editor's canvas can push draft content into a page that is supposed to be frozen — the reviewer's link and the editor's view then disagree. Gate that import on edit mode, and make sure edit mode is false when `status === "snapshot"`. Also check your locale-redirect layer: if the site 301s prefix-less paths onto a locale prefix, a snapshot URL passes through it like any page. That is fine, as long as the redirect preserves the path and the redirected request still runs the lookup above. ## What you are not building Worth stating, because the SDK path has all of these and this one has none: * No `/snapshot/[token].astro` page and no route registration — the snapshot path *is* a URL your resolver already handles. * No `snapshotToken` query and no token validation — you match on `url`, and an unknown token simply matches nothing. * No expiry logic. * No new dependency or SDK version bump. ## Verify it end to end 1. In Strife, open a page with unpublished changes and create a snapshot. Copy the link. 2. Open it in the language the snapshot was created from → the page renders in your normal design, with the draft's content, plus your banner if you added one. 3. Open the same token under a different locale prefix → your ordinary 404. (Exact locale only, by design.) 4. Load a listing that includes the page → the snapshot is not in it, and the token appears nowhere in the HTML. 5. Revoke the snapshot in Strife, wait a moment, reload → 404. 6. Check the response headers from step 2 against the table above. If step 2 renders the *published* version instead of the draft, your lookup found the canonical row first: the snapshot branch is missing from the query that actually resolved the page, or a second by-URL query downstream re-resolved it with the published-only predicate. --- # Purge your CDN cache when content changes Source: https://strife.app/docs/how-to-guides/purge-cdn-cache Keep a CDN or caching proxy in front of a Strife site fresh: a cache lifetime as the safety net, and a webhook receiver that purges exactly the pages that changed. Works with any CDN; Bunny is built in. A CDN in front of your site makes pages fast, until an editor publishes and visitors keep getting the old page. Three layers keep it fresh. Each one helps on its own. 1. **A cache lifetime** caps how stale a page can get, even if a purge is lost. 2. **A webhook receiver** purges the pages an event names, seconds after the change. 3. **Shorter lifetimes, or cache tags, for pages that only show other content.** Home pages, listings and menus aren't named in any event. ## 1. Give every page a lifetime Send a `Cache-Control` header that lets the CDN keep a page for a few minutes and keep serving it while it fetches a new one: ``` Cache-Control: public, max-age=0, s-maxage=300, stale-while-revalidate=86400 ``` * `s-maxage=300`: the CDN may serve its copy for 5 minutes, whatever happens to a purge. * `max-age=0`: browsers always ask again, so a purge reaches visitors at once. * `stale-while-revalidate`: after those 5 minutes the CDN answers from its copy while it fetches a fresh one, so visitors never wait for your server. Set the lifetime per route. Pages that list or link to other content (a home page, a news listing) benefit from a shorter one, because no event names them. ## 2. Purge on webhooks Add a webhook with the **Custom endpoint** provider, your receiver's URL, a signing secret you choose, and the events **Content published**, **Content unpublished** and **Site changed** (see [Webhooks](https://strife.app/docs/reference/webhooks.md)). The receiver: 1. **Verifies the signature** over the raw body, and answers `401` if it doesn't match. 2. **Skips a delivery it has already handled** (`X-Strife-Delivery`). Events can arrive twice. 3. **Purges.** * `scope` is `site`: purge the whole site. * Otherwise: purge every path in `urls` on its language's host, and every path in `previousUrls` on every host. Old slugs and pages that were taken down are in `previousUrls`. 4. **Answers `502` if the CDN call fails**, so Strife tries again. A `4xx` would end the retries. This one runs as a Cloudflare Worker and purges by URL. Only `purgeUrls` and `purgeEverything` are specific to Cloudflare; swap them for your CDN's API. ```js title="strife-purge.js" // Your site's address per language. A single-host site maps every language to it. const HOSTS = { en: 'https://example.com', sv: 'https://example.com/sv' }; export default { async fetch(request, env) { const raw = await request.text(); // verify the RAW body, before parsing if (!(await verify(raw, request.headers.get('X-Strife-Signature'), env.STRIFE_WEBHOOK_SECRET))) { return new Response('bad signature', { status: 401 }); } const delivery = request.headers.get('X-Strife-Delivery'); if (await env.SEEN.get(delivery)) return new Response('duplicate'); const event = JSON.parse(raw); try { if (event.scope === 'site') { await purgeEverything(env); } else { const urls = [ ...Object.entries(event.urls ?? {}).map(([locale, path]) => (HOSTS[locale] ?? HOSTS.en) + path), ...(event.previousUrls ?? []).flatMap((path) => Object.values(HOSTS).map((host) => host + path)), ]; await purgeUrls([...new Set(urls)], env); } } catch { return new Response('purge failed', { status: 502 }); // Strife retries a 5xx } await env.SEEN.put(delivery, '1', { expirationTtl: 86400 }); return new Response('ok'); }, }; async function verify(raw, header, secret) { if (!header?.startsWith('sha256=')) return false; const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); const mac = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(raw)); const expected = [...new Uint8Array(mac)].map((b) => b.toString(16).padStart(2, '0')).join(''); const given = header.slice('sha256='.length); // Constant-time compare. let diff = expected.length ^ given.length; for (let i = 0; i < Math.min(expected.length, given.length); i++) diff |= expected.charCodeAt(i) ^ given.charCodeAt(i); return diff === 0; } async function purgeUrls(files, env) { for (let i = 0; i < files.length; i += 30) { // Cloudflare takes up to 30 URLs per call on most plans await cloudflare({ files: files.slice(i, i + 30) }, env); } } const purgeEverything = (env) => cloudflare({ purge_everything: true }, env); async function cloudflare(body, env) { const response = await fetch(`https://api.cloudflare.com/client/v4/zones/${env.CF_ZONE}/purge_cache`, { method: 'POST', headers: { Authorization: `Bearer ${env.CF_TOKEN}`, 'Content-Type': 'application/json' }, body: JSON.stringify(body), }); if (!response.ok) throw new Error(`purge ${response.status}`); } ``` > [!NOTE] > **Using Bunny?** Strife can purge a Bunny pull zone itself, with no receiver of your own. Turn on the Bunny integration in the team's integration settings, with an API key from your Bunny account. Strife purges the same URLs a receiver would, on the site addresses configured for the team, and purges the whole site on `site.changed`. ## 3. Pages that only show other content `urls` and `previousUrls` name a document's own pages. A news listing, a home page that shows the latest articles, or a menu on every page also changes when an article is published, but no event names them. Either: * **Give those routes a short lifetime** (step 1). That is the simplest, and often enough. * **Purge by tag**, on a CDN that supports it (Cloudflare `Cache-Tag`, Fastly `Surrogate-Key`, Bunny `CDN-Tag`). Have your renderer tag each response with the documents and collections it read, e.g. `doc:` and `col:`. Then purge `doc:` and `col:` from the event, as well as its URLs. --- # Known issues Source: https://strife.app/docs/how-to-guides/known-issues Known issues when you build a site with Strife or preview it in Studio, and how to work around them. --- # Previewing with 100vh sections Source: https://strife.app/docs/how-to-guides/known-issues/previewing-with-100vh-sections Websites with 100vh sections may appear unnaturally extended in the Strife Studio preview, causing a display issue. To resolve this issue, you can utilize CSS media queries to reset the height of 100vh sections to 'initial,' specifically targeting larger screens or heights. This ensures that the original website remains unaffected, except when displayed on very large screens, which is likely to result in an improved user experience. Refer to the code example below for a practical demonstration of this solution. ```css @media (min-height: 1600px) { body { height: initial; } main { height: initial; } section { min-height: initial; } } ``` --- # React, className and class using web components Source: https://strife.app/docs/how-to-guides/known-issues/react-classname-and-class-using-web-components --- # CLI Source: https://strife.app/docs/reference/cli The Strife CLI (@strifeapp/cli) connects a local project to Strife: sign in, link a team, define content types in code, and deploy them — from the command line or as part of CI. Strife CLI is the code-first bridge between your project and Strife. It handles authentication, links a local project to a team, and deploys a code-defined content model to that team's templates — no manual template setup in Strife Studio required. > [!NOTE] > **Status:** the CLI is in active development (`0.x`, alpha). The surface area described here is stable enough for day-to-day use, but may still change between minor versions. Pin an exact version in CI. At a glance, the CLI lets you: * Authenticate via a browser-based device flow (`strife login`) — no passwords or API keys typed into a terminal. * Link a local project to a specific team (`strife link`), or bootstrap a brand-new project end to end in one step (`strife` / `strife .`). * Define content types in TypeScript or JavaScript using [`defineType`](https://strife.app/docs/reference/cli/schemas.md) instead of building templates by hand in Strife Studio. * Generate local TypeScript types for your content model (`strife typegen`) — see [Typegen](https://strife.app/docs/reference/cli/typegen.md). * Deploy your code-defined schema as real templates, ready to edit in Strife Studio (`strife push`). * Upload media directly to a team's asset library (`strife upload`). See [Commands](https://strife.app/docs/reference/cli/commands.md) for the full command reference, [Schemas](https://strife.app/docs/reference/cli/schemas.md) for `defineType`/`defineConfig`, [Typegen](https://strife.app/docs/reference/cli/typegen.md) for generated types, and [Authentication & Linking](https://strife.app/docs/reference/cli/authentication-and-linking.md) for how sign-in and project linking work under the hood. ## Requirements * Node.js 22 or later. * An ESM-compatible project (`"type": "module"` in `package.json`, or ESM-flavored config files). The CLI itself is published as ESM. The CLI does not assume any particular frontend framework. Everything in this section — authentication, linking, schema authoring, `push`, `typegen` — is plain Node.js tooling that works the same way regardless of what renders your site. ## Install Add the CLI and the Strife SDK to your project as dev dependencies: ```sh npm install --save-dev @strifeapp/cli @strifeapp/strife ``` > [!NOTE] > `strife push` and `strife typegen` always resolve their schema/type-generation implementation from **your project's own installed `@strifeapp/strife`** — not a copy bundled with the CLI — the same way the vite/astro CLIs use your project's installed framework rather than a bundled copy. This holds regardless of whether you use live-preview: `@strifeapp/strife` is required for `push`/`typegen` to run at all, not just for runtime/live-preview integrations. > > `@strifeapp/strife/schema` already re-exports everything `@strifeapp/schema` provides (`defineType`, `fields`, `defineConfig`, `glob`), so there's normally no reason to add `@strifeapp/schema` as its own direct dependency — import from `@strifeapp/strife/schema` and let `@strifeapp/strife` pull it in transitively. If `@strifeapp/strife` is missing (for example, a project that installed only `@strifeapp/schema`), `push`/`typegen` fail immediately with a clear "Could not resolve `@strifeapp/strife`" error. Install the CLI as a **dev dependency**, not globally. Global installs work too, but every command in this documentation uses `npx strife ...`, which finds your project's locally installed binary regardless of whether a global install also exists — the portable form to use in scripts, CI, and instructions you hand to teammates. A bare `strife` (no `npx`) only works if the CLI happens to be installed globally on that specific machine. ## Quickstart ```sh # 1. Authenticate — prints a URL to open (does not launch a browser for you) npx strife login # 2. Link this directory to a workspace + team npx strife link # 3. Declare a content type mkdir schemas cat > schemas/article.ts <<'EOF' import { defineType, fields } from '@strifeapp/strife/schema'; export const article = defineType({ name: 'articles', title: 'Article', type: 'document', fields: { heading: fields.text({ label: 'Heading', localizable: true }), body: fields.html({ label: 'Body' }), }, }); EOF # 4. Point the CLI at your schema files cat > strife.config.ts <<'EOF' import { defineConfig, glob } from '@strifeapp/strife/schema'; export default defineConfig({ schema: glob('./schemas/**/*.ts'), }); EOF # 5. Deploy it npx strife push ``` After `push` completes, the `Article` type is a real, editable template in Strife Studio. ## Bootstrapping a brand-new project If you're starting from scratch rather than adding the CLI to an existing project, running the CLI with no arguments (or `strife .`) drives the whole setup interactively — sign-in, team selection or creation, an optional starter template, and writing the local credentials your app needs to connect to the team's database: ```sh npm create @strife # or, if @strifeapp/cli is already installed: npx strife ``` Both invocations run the exact same logic. `npm create @strife` is a thin wrapper that (optionally) creates a target directory and then delegates straight into it. What it does, step by step: 1. Signs you in (device flow), unless you already have a valid session. 2. Resolves a team: link to one you already have access to, or create a new one by name. (Skipped if the current directory is already linked.) 3. If the directory is empty and you're in an interactive terminal, optionally scaffolds a starter project — currently Astro-based starters only (tagged `strife-starter` under the `nimble-initiatives` GitHub org, discovered at runtime). If you're adding Strife to an existing project, run this from that project's directory instead: since it isn't empty, the starter prompt is skipped automatically and you go straight to linking. 4. Provisions a database client certificate for the team and writes a single `STRIFE_SECRET` value to `.env`, packing the connection details your app needs at runtime (database URLs, certificate, password). `.env` is added to `.gitignore` automatically. 5. If a starter was scaffolded, runs `typegen generate` and `push` for you and seeds some initial content; otherwise, it's on you to run `strife push` once you've written a schema. > [!NOTE] > `strife login`/`link`/`setup` only ever store non-secret linkage info (workspace/team IDs) in `.strife/project.json`, which is safe to commit — it's added to `.gitignore` mainly as a convenience, and contains no credentials. The actual secret lives only in `.env`. ## Troubleshooting **A bare `strife` command works for me but not for a teammate.** `npm install --save-dev` never puts a binary on your system `PATH` — only in that project's `node_modules/.bin/`. If `strife` (without `npx`) works for you specifically, you most likely also have `@strifeapp/cli` installed globally on your machine from something unrelated. Don't assume teammates have the same global install; use `npx strife ...` in any instructions you hand off, and it will resolve correctly whether or not a global install exists. For live-preview issues (e.g. the preview panel not loading your local dev server), see [Live preview](https://strife.app/docs/reference/live-preview.md#troubleshooting) — that's general Strife Studio behavior, not specific to the CLI. --- # Commands Source: https://strife.app/docs/reference/cli/commands Full reference for every strife command — syntax, flags, authentication requirements, and what each one does. Run `strife --help` at any time for a summary of the same information. ### Global behavior * `--help` / `-h` and `--version` / `-v` are only recognized **before** the command name (`strife --help` works; `strife push --help` does not — it's passed through to `push`, which ignores it). * `--json` is **not** a global flag. Pass it after the command name on commands that support it (`strife whoami --json`), not before. * `--non-interactive` suppresses prompts and browser-open attempts, for scripts; some commands require an existing link when run this way, since there's nothing to prompt for otherwise. It does not sign you in: commands that talk to Strife still need a `strife login` session, which a CI runner cannot get today — see [Non-interactive use](https://strife.app/docs/reference/cli/authentication-and-linking.md#non-interactive-use). * Running an unrecognized command prints an error and exits with a non-zero status. * Set `STRIFE_NO_BANNER=1` to suppress the startup banner (useful when wrapping `strife` in scripts). ### Authentication requirements by command | Command | Requires login | Requires link | | --------------------------------------- | ---------------------------- | ----------------------------- | | `login` | — (that's its job) | no | | `logout` | no | no | | `whoami` | yes | no (degrades gracefully) | | `link` | yes | — (that's its job) | | `push` | yes | yes | | `upload` | yes | yes | | `setup` (bare `strife` / `strife .`) | bootstraps sign-in if needed | no (establishes it) | | `teams ls` / `teams rm` | yes | no | | `domains` / `domains set` | yes | yes | | `folders create` | yes | only if `--team` isn't passed | | `typegen generate` / `typegen validate` | no | no — fully offline | ## `strife login` ``` strife login [--api-url ] [--force] ``` Authenticates via an OAuth 2.0 Device Authorization Grant. The CLI does not open a browser for you — it prints a URL and a code to visit. If you already have a valid session, `login` does nothing unless you pass `--force` (useful for switching accounts or workspaces, since a login session is scoped to one workspace for its lifetime). | Flag | Description | | ----------------- | ------------------------------------------------------------------------------------- | | `--api-url ` | Override the API base URL. Defaults to `$STRIFE_API_URL` or `https://api.strife.app`. | | `--force` | Re-authenticate even if a valid session already exists. | ## `strife logout` ``` strife logout [--json] ``` Revokes the current session server-side on a best-effort basis and always clears local credentials — it exits successfully even if the machine was already logged out, or if the server-side revoke call fails. Does not remove any directory's `.strife/project.json` link; a previously linked directory still shows as linked, it just can't authenticate until you log in again. ## `strife whoami` ``` strife whoami [--json] ``` Prints the signed-in user, the active workspace/team (read from the current directory's link, not from the session token), and when the session expires. ## `strife link` ``` strife link [--workspace ] [--team ] [--force] ``` Links the current directory to a team, writing `.strife/project.json`. The workspace is fixed by your login session — there's no workspace picker here, only a team picker. If the target workspace has no teams yet, `link` fails; create one first (see [bootstrapping a new project](https://strife.app/docs/reference/cli.md#bootstrapping-a-brand-new-project)). | Flag | Description | | ------------------------ | ------------------------------------------------------------------------------------------------------------ | | `--workspace ` | Assert which workspace you expect to link into. Errors if it doesn't match your session's workspace. | | `--team ` | Pick a team non-interactively. Required in `--non-interactive` mode if the workspace has more than one team. | | `--force` | Relink even if the directory is already linked. | `.strife/project.json` contains only non-secret identifiers (workspace/team IDs and names) and is safe to commit. ## `strife push` ``` strife push [--config ] [--dry-run] [--force] [--prune] [--allow-missing-ids] [-y | --yes] ``` Compiles the schema files described by `strife.config.ts` (see [Schemas](https://strife.app/docs/reference/cli/schemas.md)) and deploys them to the linked team: templates are upserted by id, followed by deployment of the content index and, if configured, the team's localization settings. Before reading the schemas it loads `.env.local` and `.env` from the current directory into the environment (never overriding a variable the shell already set), so a schema can read `process.env`; in a directory linked to a team, the lines prefixed with the team's key (`ACME_BLOG_PAGE_ID`) stand in for the plain name — see [Placing pages under a specific page](https://strife.app/docs/reference/cli/schemas.md#placing-pages-under-a-specific-page). They are removed again once the schemas are loaded, so nothing in `.env` changes how the CLI itself talks to Strife. A field under a name Strife keeps its own properties under (`id`, `status`, `archived`, …) stops the push before anything is sent, and a name the content index fills itself (`url`, `publishedAt`, …) prints a warning; see [Don't shadow the built-in `Content` fields](https://strife.app/docs/reference/cli/schemas.md#dont-shadow-the-built-in-content-fields). | Flag | Description | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | `--config ` | Path to a config file other than the project root's `strife.config.ts` — useful in monorepos. | | `--dry-run` | Print the compiled output without deploying anything. Its only request is a read of the team's current templates, to warn about `baseProperties` flags the push would turn off; if that read fails, the dry run still completes. | | `--force` | Skip the optimistic-concurrency check (see below) and push regardless of whether the team's templates changed since you last checked. | | `--prune` | Also archive templates that exist on the team but aren't in this push (see below). Off by default. | | `--allow-missing-ids` | Push even when a `from: { id: process.env.X }` entry, or the `group: { id: process.env.X }` of a [`fields.labels()`](https://strife.app/docs/reference/field-reference/fields.labels.md#limit-the-field-to-one-label-group) field, reads an unset variable: the id is left out, with a warning. Without it such a push is refused (also under `--dry-run`, after the compiled output), so a template cannot silently lose its parent, nor a label field its group. | | `-y`, `--yes` | Skip the confirmation prompt. Required in `--non-interactive` mode. | From `@strifeapp/cli` 0.1.20, a schema with a deprecated [`fields.reference()`](https://strife.app/docs/reference/field-reference/fields.reference.md) field is refused before anything is sent, also under `--dry-run`. Use `fields.related()` instead, under the same key. **Push upserts by id; it does not delete by omission unless you ask it to.** Every deploy is checked against the team's current state via a version fingerprint; if something else changed the team's templates since your last check, `push` fails with a conflict rather than silently overwriting (`--force` bypasses this). By default, templates that exist on the team but aren't present in your local schema are left untouched — a teammate working from a different branch, with a different subset of schemas, can push without affecting templates they simply don't have locally yet. Pass `--prune` to opt into the old full-replace behavior instead: templates missing from the push are archived, not deleted, so they can be restored by pushing them again. `--prune` is meant for a deliberate, occasional cleanup sweep — run from your default branch, coordinated with anyone else who might be pushing — not as part of routine day-to-day pushes. > [!WARNING] > Choose type `name`s that are unlikely to collide with what teammates are independently defining. Two different local schemas that both resolve to the same template — for example, two people separately defining a type named `Home` — deploy to the same underlying document, which can produce confusing results if pushed independently rather than as one shared schema. ## `strife upload` ``` strife upload [--folder ] [--workspace ] [--name ] ``` Uploads one or more local files to the linked team's media library, directly to storage (not proxied through the Strife API). All files are validated up front — a missing or unsupported file anywhere in the batch aborts before anything uploads. Video files are rejected client-side (and server-side) by extension. | Flag | Description | | ------------------ | -------------------------------------------------------------- | | `--folder ` | Target folder. Defaults to the team's root. | | `--workspace ` | Attribute the upload to a workspace other than the linked one. | | `--name ` | Display name. Only applies when uploading a single file. | ## `strife` / `strife .` (setup) No arguments — see [bootstrapping a brand-new project](https://strife.app/docs/reference/cli.md#bootstrapping-a-brand-new-project) in the overview. ## `strife teams` ``` strife teams ls strife teams rm [-y | --yes] ``` `ls` lists the teams in your current workspace. `rm` **permanently** deletes a team — its database, storage, and certificates — after a confirmation prompt (skip with `--yes`). ## `strife domains` ``` strife domains strife domains set ``` Shows or sets the linked team's site origin. `set` requires an absolute `http(s)` URL. ## `strife folders create` ``` strife folders create [-p | --parent ] [--team ] [--json] ``` Creates a media library folder. Uses the linked team unless `--team` is given. ## `strife typegen` ``` strife typegen generate [--config ] [-o | --output ] strife typegen validate [--config ] [-o | --output ] [--allow-missing-ids] ``` See [Typegen](https://strife.app/docs/reference/cli/typegen.md) for the full reference — both subcommands are fully offline and require neither authentication nor a linked project. Like `push`, both load `.env.local` and `.env` from the current directory before reading the schemas, and in a directory linked to a team they read that team's prefixed lines the same way. --- # Schemas Source: https://strife.app/docs/reference/cli/schemas Define content types in code with defineType and fields, and register them with strife.config.ts — an alternative to building templates by hand in Strife Studio. `defineType` and the `fields.*` builders are a code-first way to define the same templates you could otherwise build in Strife Studio's UI. Import them from `@strifeapp/strife/schema`, which re-exports everything in `@strifeapp/schema`; there is no need to add `@strifeapp/schema` as a dependency of its own (see [CLI](https://strife.app/docs/reference/cli.md)). A type defined with `defineType` compiles to the same underlying template format described in [Defining Templates with JSON](https://strife.app/docs/reference/templates/defining-templates-with-json.md) — `defineType` is a typed, ergonomic authoring layer on top of that format, not a different concept. ## `defineType` ```ts import { defineType, fields } from '@strifeapp/strife/schema'; export const article = defineType({ name: 'articles', title: 'Article', type: 'document', fields: { heading: fields.text({ label: 'Heading', localizable: true }), body: fields.html({ label: 'Body' }), image: fields.image({ label: 'Image', width: 1600, height: 900, format: 'webp' }), }, }); ``` | Option | Description | | ------------- | ---------------------------------------------------------------------------------------------------------------- | | `name` | Required. The type's identifier. Drives the default `collection` name (pluralized, e.g. `article` → `Articles`). | | `title` | Label shown in Strife Studio. Defaults to a title-cased version of `name`. | | `type` | `'document'` (default), `'content'`, or `'file'`. See [Type kinds](https://strife.app/docs/reference/cli/schemas.md#type-kinds) below. | | `fields` | An object mapping field names to `fields.*` builders. | | `collection` | Override the derived collection name. | | `description` | Shown as a hint to editors in Strife Studio. | | `icon` | Icon name shown in Strife Studio. See [Icons](https://strife.app/docs/reference/icons.md). | | `composable` | Whether content built from this type can be composed inside other documents. Defaults to `true`. | | `from` | The document type(s) pages of this type are created under, and/or a specific page by id. See [Placing pages under a parent type](https://strife.app/docs/reference/cli/schemas.md#placing-pages-under-a-parent-type) and [under a specific page](https://strife.app/docs/reference/cli/schemas.md#placing-pages-under-a-specific-page). | | `baseProperties` | Whether the built-in `displayName` and `slug` have one value per locale: `{ displayName: { localizable: true }, slug: { localizable: true } }`. Leave one out to keep Strife's default: `slug` is localizable on a team with two or more locales, and `displayName` follows each document's stored name — per locale when it already has one per locale, otherwise shared. See [Localizable `displayName` and `slug`](https://strife.app/docs/reference/cli/schemas.md#localizable-displayname-and-slug). | `defineType` doesn't do anything at runtime beyond returning its input — the value comes from the types it produces for the rest of your code (see [Typegen](https://strife.app/docs/reference/cli/typegen.md)) and from `strife push` compiling it into a real template. ### Type kinds | `type` | Has its own URL | Typical use | | ---------- | --------------- | ----------------------------------------------------------------------------------------- | | `document` | yes | A standalone page — a blog post, a product, a landing page. | | `content` | no | A reusable block composed inside a document or a [Chapters](https://strife.app/docs/reference/fields/chapters.md) field. | | `file` | no | File-shaped content. Wire `templateType: 'ft'`. | ### Singleton documents `composable: false` is the right way to model a singleton document type — a root `Home`, a global `Navigation` or settings document, anything that should only ever have one instance. It's not just a hint: Strife Studio's "create new document" action filters on `composable`, so a `composable: false` document template doesn't offer a create action once its one document exists. `composable: false` also compiles to `filterable: false`, which keeps the type out of the content list's **Collection** filter in Studio's classic interface. Studio's new interface offers a document type in that filter as soon as it has a document, so the singleton can be filtered for there. > [!NOTE] > For settings that are not a page, such as the navigation, the footer or the site's contact details, use a [global config](https://strife.app/docs/reference/globals.md) instead. A global needs no document id in your site's configuration and is not listed among the content. ```ts export const navigation = defineType({ name: 'navigation', type: 'document', composable: false, fields: { /* ... */ }, }); ``` `disableURL` isn't a `defineType` option — it's derived automatically from `type` (`false` for `document`, always `true` otherwise). This is deliberate: document types are standalone pages and get a URL by default; content and file types aren't pages and don't. There's no case where overriding it makes sense, so it isn't exposed. ### Placing pages under a parent type Every page has an origin — the parent it sits under in the content tree, which drives its URL, breadcrumbs and where it is listed. `from` tells Strife which document type(s) a page of this type belongs under, so editors don't have to know. Give it a `defineType` name, or several: ```ts export const blogPost = defineType({ name: 'blogPost', from: 'blog', // or ['blog', 'newsRoom'] fields: { /* ... */ }, }); ``` In Strife Studio this shapes the origin picker, both when composing a page and when changing a page's origin from the content list: * exactly one page of a `from` type exists — it is preselected; * several exist — the picker offers only those; * none exist — the picker behaves as before, with a hint naming the expected parent type. Composing from a row's Compose menu keeps that row as origin only when it is of a `from` type, and the menu lists only templates allowed under that row. `from` is a Studio-side rule, not a server-side one: existing content is untouched and the API still accepts any origin. It applies in both of Strife Studio's interfaces and to the MCP `create_draft` tool. Studio's new interface has no origin picker: a new page goes under the page the editor has highlighted in the content list when that page is allowed, otherwise under the one allowed page when there is exactly one, and otherwise under the team's home page (the page whose slug is `/`), or at the top level when there is none; its **Move to** offers only the allowed pages. In `create_draft`, an omitted `origin` defaults to the one page of an allowed type, several such pages make the tool ask for `origin`, and none falls back to the team's home page, or the top level when the team has none. A page of a `from` type never becomes the home page itself. It does nothing for a type whose documents have no URL (`disableURL`, i.e. content and file types), and an empty list means unrestricted. It compiles to the template's `allowedOrigins` (the parent types' normalized names) and needs `@strifeapp/strife` 1.13.0 or later, which brings `@strifeapp/schema` 0.13.0; on an older version `from` is simply not a known option. #### Placing pages under a specific page Sometimes the parent is one particular page rather than a kind of page — the blog, which is one of several list pages. Name it by id with `{ id }`, alone or mixed with type names: ```ts export const blogPost = defineType({ name: 'blogPost', from: { id: process.env.BLOG_PAGE_ID }, // or: from: ['newsRoom', { id: process.env.BLOG_PAGE_ID }] fields: { /* ... */ }, }); ``` A page id belongs to one team — the blog page has one id in your development team and another in production — so it is read from the environment rather than written into the schema. Give each team its own line, prefixed with the team's key: ``` # .env.local (or .env) — one line per team ACME_BLOG_PAGE_ID=f375a22c-3142-4dbf-90ad-00bd9fee9e97 ACMEDEV_BLOG_PAGE_ID=5d0c2b7e-8a41-4f6e-b3d9-7c1e2a9f4b60 ``` `strife push` and `strife typegen` load `.env.local` and `.env` from the directory they run in — the project root, where `strife.config.ts` lives — before reading the schemas. In a directory linked to a team (`strife link`), the lines prefixed with that team's key then stand in for the plain name: a push to ACME reads `ACME_BLOG_PAGE_ID` as `BLOG_PAGE_ID`, a push to ACMEDEV reads `ACMEDEV_BLOG_PAGE_ID`, and each team's template carries only its own page. The prefix is the team key that `strife whoami` shows after the team name, upper-cased, with any character other than A–Z, 0–9 and `_` written as `_`. `strife push` shows the mapping on its `Environment:` line — `Environment: .env.local · ACME_BLOG_PAGE_ID → BLOG_PAGE_ID` — or `no ACME_ variables` when there is none for that team, in which case a plain `BLOG_PAGE_ID` from the files goes out. A plain `BLOG_PAGE_ID` works too. A value already set in the environment wins over everything, which suits a one-off push; then comes the linked team's line, then a plain line in `.env.local`, then one in `.env`. A tool that loads `.env` before the CLI starts (direnv, dotenv-cli, Bun) puts its plain lines in the environment too, so `strife push` warns whenever a value from the environment keeps the team's line from being used. Per-mode files such as `.env.production` are not read: a push builds nothing, so it has no mode — the team it goes to picks the value, through the prefix. This works with any framework. Only the CLI reads the id: an app that imports the schema file on the server still loads it without the variable, with the id left out (not in a browser bundle, where `process` does not exist). Use `process.env`, not `import.meta.env`, which does not exist when the CLI loads the schema. To copy a page's id, open its row menu in Strife Studio's content list and choose **Copy ▶ Copy ID**, or run *Copy ID* from the command menu (Ctrl/Cmd+K) when that row is selected; **Copy typename** next to it gives the page's type name. The id is also the last part of the page's address in the classic interface (`/team//`), and the `find_content` tool in the MCP tools returns it as well. Studio's origin picker and the MCP `create_draft` tool treat a page named by id the way they treat a type: when it is the only match it is preselected (for `create_draft`, it becomes the origin), and when the schema also names a type, the pages of that type are offered alongside it (`create_draft` then asks which one). When the id names no page in the current team (the variable holds another team's id, or the page was deleted), the picker falls back to the full list and the hint names the id it looked for, and `create_draft` places the draft under the team's home page (or at the top level when there is none) with a note naming the id. In Studio's new interface, a page named by id is a parent like any other allowed page: as the only match it becomes the parent of a new page, and when it names no page in the team, new pages go under the home page. An unset variable never breaks compilation — the id is simply left out — but `strife push` and `strife typegen validate` refuse to continue when that happens (`blogPost: from.id is undefined — …`, naming the linked team's prefixed form), because the template would otherwise reach the team without its parent rule and nobody would notice; `push --dry-run` prints the compiled output before it refuses. Pass `--allow-missing-ids` to push or validate anyway, with the id left out and the warning kept, for a team where that page deliberately does not exist. `strife push` needs a `strife login` session, and a CI runner cannot get one today: login happens in a browser, and every refresh replaces the session's refresh token and retires the old one, so a session copied to a runner stops working at its first refresh. So pushes run from a developer's machine. `strife typegen validate` runs anywhere, CI included, but a CI checkout is usually not linked to a team (`strife link` keeps `.strife/` out of git), so no team line applies there unless you commit `.strife/project.json`: set the plain variable in the CI environment, or pass `--allow-missing-ids`. It compiles to the template's `allowedOriginIds` and needs `@strifeapp/strife` 1.14.0 or later, which brings `@strifeapp/schema` 0.14.0 (update that too if you import from it directly), plus `@strifeapp/cli` 0.1.0-alpha.16 or later for the `.env` loading and the refusal, and 0.1.0-alpha.17 or later for the team lines. With an older `@strifeapp/strife`, a `{ id }` entry fails to compile with a clear error; with an older CLI, no `.env` file is loaded and nothing stops a push whose variable is unset, and 0.1.0-alpha.16 reads only the plain name. ### Fields `fields.*` builders map to the same editor components documented under [Fields](https://strife.app/docs/reference/fields.md). Every builder has its own page with the full option set and output type under [Field Reference](https://strife.app/docs/reference/field-reference.md) — the table below is a quick index: | Builder | Editor | Notes | | ------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`fields.text(...)`](https://strife.app/docs/reference/field-reference/fields.text.md) | Text | | | [`fields.paragraph(...)`](https://strife.app/docs/reference/field-reference/fields.paragraph.md) | Paragraph | | | [`fields.number(...)`](https://strife.app/docs/reference/field-reference/fields.number.md) | Number | | | [`fields.slider(...)`](https://strife.app/docs/reference/field-reference/fields.slider.md) | Slider | `min`/`max`/`step` configure the range (defaults 0–100, step 1). | | [`fields.html(...)`](https://strife.app/docs/reference/field-reference/fields.html.md) | Rich Content | `marks`/`nodes` control available formatting/content; `nodes` also carries image size/style/quality presets. | | [`fields.date(...)`](https://strife.app/docs/reference/field-reference/fields.date.md) / `fields.date({ withTime: true })` | Date / Date Time | | | [`fields.switch(...)`](https://strife.app/docs/reference/field-reference/fields.switch.md) / [`fields.toggle(...)`](https://strife.app/docs/reference/field-reference/fields.toggle.md) | Checkbox / Toggle | | | [`fields.slug(...)`](https://strife.app/docs/reference/field-reference/fields.slug.md) | Slug | | | [`fields.select(...)`](https://strife.app/docs/reference/field-reference/fields.select.md) | Combo Box | | | [`fields.multiSelect(...)`](https://strife.app/docs/reference/field-reference/fields.multiselect.md) | Multi Select | Requires `options`. Stores an array of selected `value`s — distinct from `select({ multiSelect: true })`, which stores `{ value, name }` objects. | | [`fields.labels(...)`](https://strife.app/docs/reference/field-reference/fields.labels.md) | Label | Picks from the team's labels, grouped for browsing — the same picker used for the built-in `labels` base property. `group: { id }` limits it to one label group's labels. Adds an *additional*, independently-valued label-style field, distinct from `labels`. | | [`fields.radioGroup(...)`](https://strife.app/docs/reference/field-reference/fields.radiogroup.md) | Radio Group | | | [`fields.image(...)`](https://strife.app/docs/reference/field-reference/fields.image.md) / [`fields.imageGroup(...)`](https://strife.app/docs/reference/field-reference/fields.imagegroup.md) | Image / Image Group | `image` requires `width`/`height`/`format`. `height: 'auto'` gives a width-only image that keeps the source aspect ratio (compiles to the template's numeric `height: 0`). | | [`fields.video(...)`](https://strife.app/docs/reference/field-reference/fields.video.md) | Video | Read type is `unknown` — stored shape isn't finalized yet. | | [`fields.assets(...)`](https://strife.app/docs/reference/field-reference/fields.assets.md) | Assets | `accept` restricts to `'image/*' \| 'video/*' \| 'file/*'` (translated to numeric wire codes); `size` caps the count. | | [`fields.link(...)`](https://strife.app/docs/reference/field-reference/fields.link.md) | Link | `linkOnly` hides the link-text input for href-only links. | | [`fields.serp(...)`](https://strife.app/docs/reference/field-reference/fields.serp.md) | Serp | Usually `localizable: true` — title/description are typically per-locale. No `searchable`/`filterable`. | | [`fields.reference(...)`](https://strife.app/docs/reference/field-reference/fields.reference.md) | Related | Deprecated: `fields.related(...)` replaces it in an upcoming release, and `strife push` refuses it from CLI 0.1.20. | | [`fields.references(...)`](https://strife.app/docs/reference/field-reference/fields.references.md) | References | `allow` sets the allowed target type(s). | | [`fields.collection(...)`](https://strife.app/docs/reference/field-reference/fields.collection.md) | Collection | Stores a query definition (`CollectionDefinition`), not resolved documents — your app runs the query at render time. Studio-UI marks this editor obsolete; see the field page before using it in new work. | | [`fields.repeatable(...)`](https://strife.app/docs/reference/field-reference/fields.repeatable.md) | Repeatable | `of` sets the repeated inner editor (`text`, `number`, `date`, `datetime`, `link`). Feature-gated per team. | | [`fields.multiInput(...)`](https://strife.app/docs/reference/field-reference/fields.multiinput.md) | Multi Input | `inputType` sets the repeated primitive input type (defaults to `text`). | | [`fields.tableInput(...)`](https://strife.app/docs/reference/field-reference/fields.tableinput.md) | Table Input | Requires `headers` and `inputTypes` — parallel arrays, one entry per column. | | [`fields.chapters(...)`](https://strife.app/docs/reference/field-reference/fields.chapters.md) | Chapters | `allow` sets the allowed content types. | | [`fields.contentTemplate(...)`](https://strife.app/docs/reference/field-reference/fields.contenttemplate.md) | Content Template | | | [`fields.tabs([...])`](../field-reference/fields.tabs.md) | Tab Group | Structural — child fields are grouped under tabs but stored flat, same as Strife stores tab data. Takes an array, not an options object. | | [`fields.hint(...)`](https://strife.app/docs/reference/field-reference/fields.hint.md) | Hint | UI-only — stores no data; omitted from the generated content type. | Each builder accepts at minimum `{ label, description?, localizable? }` plus type-specific options. > [!NOTE] > The **Notes** column above only calls out non-obvious or required options — every builder accepts more than what's shown (most also take `description`, `searchable`, `filterable`, `protected`, and `propertyName`, for example). For a builder's complete set of options — full tables, output types, and wire-format notes — open its page under [Field Reference](https://strife.app/docs/reference/field-reference.md). [Fields](https://strife.app/docs/reference/fields.md) documents the same editors from the Strife Studio UI side. Your editor's TypeScript hover/autocomplete on the `fields.*(...)` call reflects the same options straight from the source types, too. `localizable` is only available on fields where it's meaningful — text, paragraph, number, date, slug, html, image, link, serp, chapters, and contentTemplate. Fields like `switch`, `select`, and `reference` don't expose it: a boolean or a selected option isn't the kind of value that varies by locale. Turning `localizable` on for a field that already holds content keeps that content: it shows on every locale until a locale gets its own value. Update `@strifeapp/strife` before you push such a change. See [Turning `localizable` on for a field with content](https://strife.app/docs/reference/field-reference.md#turning-localizable-on-for-a-field-with-content). ### Don't shadow the built-in `Content` fields Every generated type extends a base `Content` shape that Strife already populates automatically: ```ts type Content = { id: string; docId: string; locale: string; displayName: string; url: string | null; origin: string | null; collection: string; draft: boolean; publishedAt: string | null; createdAt: string; changedAt: string; dependencies: string[]; labels: string[]; }; ``` Your fields are stored next to Strife's own document properties, so some field names are taken. The check reads the name a field is stored under (its `propertyName` when set, otherwise its key), fields inside tabs included. The label doesn't count: `externalId: fields.text({ label: 'ID' })` is fine. * **Refused:** `id`, `status`, `deleted`, `archived`, `isDraft`, `origin`, `locales`, `createdAt`, `createdBy`, `changedAt` and `changedBy`, and any name starting with `@`, `$` or `__`. Strife writes its own value under these names, such as the document's id, its publishing status, and who created and changed it and when. Some it also acts on: a document whose `archived` or `deleted` is set drops out of the content index, and publishing resets both. A field with one of these names clashes with Strife's value, so `strife push` and `strife typegen` stop before anything is sent and name every such field: ``` compile: 2 fields use names Strife reserves: field "id" can't be used: Strife keeps the document's id under that name. Rename the field, e.g. "externalId" (its label can stay "ID"). field "status" in tab "Settings" can't be used: Strife keeps the document's publishing status under that name. Rename the field (its label can stay "Status"). ``` * **Warned about:** `url`, `collection`, `publishedAt`, `locale`, `docId` and `draft`. The content index returns its own value under these names, so a field with one of them can be edited in Strife Studio but never reaches your site. `strife push` and `strife typegen validate` print a warning and carry on. A `content` type is usually a block inside Chapters, and a block keeps its own id apart from its fields. On a `content` type the refused names therefore only get a warning, since they still clash when the type is used as a document of its own. Names starting with `@`, `$` or `__` are refused there too: a block carries `$type` and `@strife` itself. `displayName`, `labels` and `dependencies` aren't checked. They are base properties, and a field under one of those names edits the document's own value, so use one only on purpose. Strife also checks the names when a template is saved, so an older CLI or the template editor in Strife Studio can't add such a field either. A field a template already has keeps saving there, but from `@strifeapp/strife` 1.21.0 on, `strife push` stops until you rename it. Values stored under the old name stay there; they don't move to the renamed field. #### Localizable `displayName` and `slug` `displayName` (the document's name) and `slug` (its URL segment) are base properties: every document has them, and they aren't in `fields`. To give either one a value per locale, say so on the type: ```ts export const article = defineType({ name: 'articles', baseProperties: { displayName: { localizable: true }, slug: { localizable: true }, }, fields: { /* … */ }, }); ``` A flag you leave out keeps Strife's default, which is how types behaved before `baseProperties` existed: `slug` is localizable when the team has two or more locales. `displayName` follows each document's stored name: a name that already has a value per locale stays per locale, and a single name stays one value shared by every locale (like a field without `localizable`); new documents start with a single name. Set `localizable: false` to turn one off, `true` to turn it on. A localizable base property is edited on each locale the document has; one that isn't keeps a single field in Strife Studio. What the type says is what `strife push` sets: the compiled template carries exactly the flags you state, and one you leave out — or delete later — goes back to the default. Upgrading `@strifeapp/strife` therefore changes no URLs. Turning a flag off deletes nothing: stored per-locale values read as the default locale's, and come back if you turn it on again. `strife push` warns about every flag it turns off (for `displayName`, only an explicit `false` turns it off), before the confirmation and under `--dry-run`, and after the push the server names the types that still hold per-locale values, with how many documents do — each with the line to add: ``` ! articles: slug is no longer localizable — 12 documents still hold per-locale values (now read as the default locale's; nothing was deleted). To make it localizable again, add to defineType: baseProperties: { slug: { localizable: true } } ``` The warning never stops the push. A push from an older `@strifeapp/strife`, which sends no flags, leaves them as they are on the server. Whatever the flag, readers get strings: the content index, the generated `Content` type (`displayName: string`), the SDK and the MCP tools resolve a localizable value to the requested locale. A locale without its own `displayName` shows the default locale's. ## `strife.config.ts` The CLI discovers your schema files through a config file at the project root — `strife.config.ts`, or `.tsx` / `.mts` / `.js` / `.mjs`: ```ts import { defineConfig, glob } from '@strifeapp/strife/schema'; export default defineConfig({ schema: glob('./schemas/**/*.ts'), }); ``` `glob()` paths resolve relative to the **config file's own directory**, not your current working directory — pass `--config ` (see [Commands](https://strife.app/docs/reference/cli/commands.md#strife-push)) to point at a config file elsewhere, for example in a monorepo: ```sh npx strife push --config packages/cms/strife.config.ts ``` ```ts defineConfig({ schema: glob('*.ts', { base: './content/types' }), }); ``` Every exported `defineType()` result across the matched files is collected automatically — you don't need to list types individually. ### Localization `defineConfig` also accepts an optional `localization` block: ```ts export default defineConfig({ schema: glob('./schemas/**/*.ts'), localization: { defaultLocale: 'en', locales: ['en', 'sv'], fallbackToPrimary: true, }, }); ``` | Option | Description | | ------------------- | -------------------------------------------------------------------------------------------------- | | `defaultLocale` | Primary locale. Must be one of `locales`. | | `locales` | Non-empty list of configured locale codes, formatted `[a-z]{2}(-[A-Z]{2})?` (`en`, `sv`, `pt-BR`). | | `fallbackToPrimary` | Optional. Whether a missing localized value falls back to the default locale. | When present, `strife push` replaces the team's entire localization configuration with this block. If you manage locales through Strife Studio already, check what's currently configured before pushing a `localization` block — it's a full replace, not a merge. Single-locale projects can omit `localization` entirely; there's no behavior change either way. ### Globals `defineConfig` also accepts an optional `globals` list: site-wide settings such as the navigation or the footer, each declared with `defineGlobal` and edited from the team menu. See [Global configs](https://strife.app/docs/reference/globals.md). ## JavaScript, not just TypeScript Everything above works identically in plain JavaScript — `defineType` and `fields.*` are ordinary functions; the type inference is authoring-time sugar for TypeScript users, not a requirement for `push` or `typegen` to work. A `strife.config.js` importing `.js` schema files behaves exactly like the TypeScript version, including the generated types. You don't lose as much editor support as you might expect by staying in `.js`. `@strifeapp/strife/schema` ships type declarations, and editors with a TypeScript language service (VS Code, for example) use them automatically for plain `.js` files that import it — autocomplete on `fields.text(...)` and friends works without any configuration. What you don't get by default is strict type _checking_ (inline errors on mistakes). Add a single `// @ts-check` comment at the top of a `.js` file to turn that on for just that file — full type checking against those types, with zero TypeScript syntax and no build step change. --- # Typegen Source: https://strife.app/docs/reference/cli/typegen Generate TypeScript types from your defineType schemas, and keep them in sync with a CI check. `strife typegen` turns your [schema definitions](https://strife.app/docs/reference/cli/schemas.md) into TypeScript types matching what the content API actually returns — useful whether or not the rest of your project uses TypeScript. Both subcommands are fully offline: no network request, no authentication, no linked project required. They only need a `strife.config.ts` and your schema files. ## `strife typegen generate` ```sh npx strife typegen generate [--config ] [-o | --output ] ``` Reads your schema files and writes TypeScript interfaces to `.strife/types.ts` (override the path with `-o`/`--output`): ```ts // AUTO-GENERATED by `strife typegen generate` — do not edit by hand. import type { Content } from '@strifeapp/types'; export interface Articles extends Content { heading: string | null; body: string; } ``` The generated shape is the **read** shape — what you get back after fetching a document, not the raw stored form. Two things follow from that: * Localized fields (`localizable: true`) collapse to the active locale as `T | null` (`null` if that locale hasn't been translated yet). Non-localized fields are plain, non-nullable types. * `reference`, `references`, `chapters`, and `contentTemplate` fields resolve to the _target_ type's own generated interface, not a raw identifier — a `reference` to your `Author` type produces `author: Author[]` rather than an opaque reference object. * `displayName` on `Content` is always a `string`, also on a type with `baseProperties: { displayName: { localizable: true } }` — the content index resolves it to the requested locale, falling back to the default locale's name. `baseProperties` changes nothing in the generated types (see [Localizable `displayName` and `slug`](https://strife.app/docs/reference/cli/schemas.md#localizable-displayname-and-slug)). This is deliberately different from the type you'd get by statically inspecting a `defineType()` call's own shape (which describes what you write into the schema, not what you read back from the content API) — the generated types are the ones to build your frontend against. ## `strife typegen validate` ```sh npx strife typegen validate [--config ] [-o | --output ] [--allow-missing-ids] ``` A CI-friendly check combining two things: 1. **Lint.** Two schemas that resolve to the same `collection` is a hard failure, and so, from `@strifeapp/cli` 0.1.20, is a deprecated [`fields.reference()`](https://strife.app/docs/reference/field-reference/fields.reference.md) field, which `push` refuses too. A `references` or `chapters` field (`reference` before 0.1.20) whose target doesn't match any locally-defined type is a warning, not a failure — the target might be defined elsewhere, e.g. authored directly in Strife Studio. A `from: { id: process.env.X }` entry whose variable is unset is a failure — the template would lose its parent rule silently — and so is a [`fields.labels()`](https://strife.app/docs/reference/field-reference/fields.labels.md#limit-the-field-to-one-label-group) field whose `group: { id }` variable is unset, which would offer every label; `--allow-missing-ids` demotes both to warnings. A field stored under a name Strife reserves fails both `generate` and `validate`, and `validate` warns about a name the content index fills itself; see [Don't shadow the built-in `Content` fields](https://strife.app/docs/reference/cli/schemas.md#dont-shadow-the-built-in-content-fields). Both `generate` and `validate` load `.env.local` and `.env` from the current directory before reading the schemas — in a directory linked to a team, with that team's prefixed lines standing in for the plain names, as in `push`. 2. **Drift.** Regenerates the types in memory and compares them byte-for-byte against the file on disk at `--output`. A missing file or any difference fails the check with a pointer to re-run `generate`. Typical usage is running `validate` in CI after `generate` has been run and committed, to catch schema changes that weren't followed by a regenerated types file. A CI checkout is usually not linked to a team (`strife link` keeps `.strife/` out of git), so no team-prefixed line applies there unless you commit `.strife/project.json`: set the plain variables that `from: { id }` and `group: { id }` read in the CI environment, or pass `--allow-missing-ids`. ## Relationship to `push` `typegen` and [`push`](https://strife.app/docs/reference/cli/commands.md#strife-push) both start from the same schema files but serve different purposes, and it's easy to conflate them: * **`typegen generate`** produces local TypeScript types only. Nothing leaves your machine. * **`push`** deploys your schema as real templates to a team in Strife Studio, plus the content index and (optionally) localization settings. Neither command touches existing content documents. --- # Authentication & Linking Source: https://strife.app/docs/reference/cli/authentication-and-linking How strife login authenticates, where credentials are stored, and how a local project gets linked to a workspace and team. ## Signing in `strife login` uses an OAuth 2.0 Device Authorization Grant: the CLI requests a device code, prints a URL and a short code, and polls in the background while you open that URL and approve the sign-in in your browser. The CLI itself never opens a browser for you or handles a password. A signed-in session consists of: * A short-lived access token (roughly 30 minutes), used to authenticate API requests. * A longer-lived refresh token (roughly 30 days), used to silently obtain a new access token as needed. It's rotated on every use. Both are stored locally — not per-project — so signing in once covers every project on that machine until the session expires or you `strife logout`. Credentials live outside your project directories entirely, in your OS's standard per-user config location, and are never committed to a repository. ## One workspace per session **Which workspace you're signed into is fixed for the lifetime of a session** — chosen when you approve the sign-in in your browser, not something the CLI lets you switch afterward. If you work across multiple workspaces (for example, your own team's workspace and a client's), use `strife login --force` to start a fresh sign-in and choose the other workspace when approving it. `strife whoami` shows which workspace and team the current session and linked directory resolve to. ## Linking a project A workspace can contain multiple teams; a local project links to exactly one team via `strife link`, which writes `.strife/project.json` in the current directory. This file: * Is looked for in the **exact directory** you run commands from — there's no upward directory search the way `git` or `npm` walk up to find a config file. Running a command from a subdirectory of a linked project reports "not linked." * Contains only non-secret identifiers (workspace ID, team ID, names) — safe to commit, though it's added to `.gitignore` automatically since it's still local, machine-specific state in most workflows. * Is unaffected by `strife logout` — logging out clears your session, not any directory's link. A previously linked directory still reports as linked; it just can't authenticate again until you sign in. Creating a _new_ team (as opposed to linking to an existing one) isn't available as its own command — it happens as part of the interactive flow when you run bare `strife` / `strife .` in an unlinked directory and choose not to link to an existing team. See [bootstrapping a new project](https://strife.app/docs/reference/cli.md#bootstrapping-a-brand-new-project). ## Non-interactive use Pass `--non-interactive` to suppress prompts. Commands that would otherwise prompt fail with an explicit error instead: * `strife link --non-interactive` requires `--team` if the workspace has more than one team. * `strife push --non-interactive` requires `-y`/`--yes`. * Anything that would need to create a new team or link for the first time requires a directory that's already linked — there's nothing to prompt for the first-time setup otherwise. Non-interactive is not unattended: every command that talks to Strife, `push` among them, needs a `strife login` session, and a CI runner cannot get one today — login happens in a browser, and every refresh replaces the session's refresh token and retires the old one, so a session copied to a runner stops working at its first refresh. Run those commands from your machine. `typegen generate` and `typegen validate` never prompt or need `--non-interactive` — they're fully offline regardless of the terminal, so they run in CI too. --- # MCP server Source: https://strife.app/docs/tools/mcp-server Connect Claude, Cursor, VS Code and other AI assistants to your Strife content with the hosted MCP server: find and read pages, write drafts, translate, manage labels, share drafts for review and publish once you approve. Strife's MCP server lets an AI assistant work with your content. Connect it, and you can ask the assistant to find a page and summarize it, write a new draft, add a translation, fill in missing alt text or share a draft for review. The assistant signs in with your Strife account, and what it writes goes into drafts, which reach your site when they are published. The one exception is making a page the home page, which changes the page itself, as it does in Studio. The server is hosted at `https://mcp.strife.app/mcp`. There is nothing to install and no key to copy: the first time your assistant connects, it opens a Strife sign-in page in your browser. > [!NOTE] > This server works with your content. To let an assistant search and read these docs, connect the [docs MCP server](https://strife.app/docs/how-to-guides/use-the-docs-from-ai-tools.md), on its own or as well. ## Connect your assistant **Claude Code** ```sh claude mcp add --transport http strife https://mcp.strife.app/mcp ``` Then run `/mcp` in Claude Code and follow the steps in your browser to sign in. Add `--scope user` to the command to have the server in every project, not only the current one. **Claude** In Claude on the web or in the desktop app, open **Customize → Connectors**, choose **+ Add → Add custom connector**, give it a name such as Strife and enter `https://mcp.strife.app/mcp` as the URL. Keep the default sign-in settings and sign in to Strife when Claude asks. On Team and Enterprise plans, an owner adds the connector first, under **Organization settings → Connectors**. Each member then finds it under **Customize → Connectors** and chooses **Connect**. **Cursor** Add the server to `~/.cursor/mcp.json` for every project, or to `.cursor/mcp.json` in one project: ```json { "mcpServers": { "strife": { "url": "https://mcp.strife.app/mcp" } } } ``` Cursor then shows that the server needs you to sign in. Follow its prompt to open the Strife sign-in page. **VS Code** Add the server to `.vscode/mcp.json` in your project, or run **MCP: Open User Configuration** from the Command Palette to have it in every workspace: ```json { "servers": { "strife": { "type": "http", "url": "https://mcp.strife.app/mcp" } } } ``` When the server starts, VS Code asks to sign in. Allow it, and sign in to Strife in your browser. Other MCP clients connect the same way: a remote server over Streamable HTTP at `https://mcp.strife.app/mcp`. The client needs to support OAuth sign-in for remote servers. Strife registers the client automatically, so there is no client ID or secret to enter. Building in [Lovable](https://strife.app/docs/tools/connect-strife-to-lovable.md)? That page has the connector dialog, what to ask for, and what a chat connector can't do. ## Sign in and choose a workspace The first time the assistant connects, your browser opens a Strife page that asks you to approve it: 1. Sign in to Strife, if you aren't already. 2. Choose the workspace to connect. 3. Check the assistant's name under **Details** and choose **Approve**. The assistant can then work in the teams of that workspace, with your account's permissions. Each connection covers one workspace. To work in two, add the server twice under different names, such as `strife-acme` and `strife-other`, and choose a different workspace for each. The assistant stays signed in until you sign it out. In Studio, **Settings → Account → Connected Agents** lists the assistants you have approved. **Revoke** stops one from renewing its access, and a token it already holds runs out within 30 minutes. To use it again, approve it again. The settings pages are only open to workspace admins today. ## What the assistant can do You don't call the server's tools yourself: the assistant picks the ones it needs from what you ask. Apart from `list_teams`, every tool takes the team to work in, by its key or id. **Teams and templates** | Tool | What it does | | --- | --- | | `list_teams` | Lists the teams in your workspace, with the keys the other tools take. | | `get_templates` | Lists a team's templates: the kinds of pages and blocks it can create. | | `get_template` | Returns one template's fields, with an example value for each and, for choice fields, the values they accept. | **Find and read content** | Tool | What it does | | --- | --- | | `find_content` | Searches by name or address, with filters on template, fields and dates. | | `list_recent_content` | Lists the most recently changed content in a team. | | `get_content` | Reads a page's fields in one language, published or draft. | | `list_drafts` | Lists the pages that have changes waiting to be published. | | `get_linkable_fields` | Lists the fields of other pages that a page can show by reference, so a page can reuse their content. | **Write drafts** | Tool | What it does | | --- | --- | | `create_draft` | Creates a page or block from a template, as an unpublished draft. | | `edit_content` | Changes a page's fields, or one part of a field: a single chapter, a list item or a key inside a value, without resending the rest. Each value is stored the way its field's editor stores it, and the result says what was adjusted. The change goes into the page's draft. | | `edit_many` | Changes up to 100 pages in one call, each with its own values. | | `add_locale` | Adds a language to a page. The assistant then writes the translation with `edit_content`. | | `discard_draft` | Throws away a page's unpublished changes, in every language. Anyone editing the page in Studio's new interface loses their undo history for it, and is told so. | Without an `origin`, `create_draft` puts a new page under the team's home page, the page whose slug is `/`. In a team without a home page, the page goes at the top level, and `origin_note` in the response says why. `create_draft` never makes the home page itself, and neither do `edit_content` and `edit_many`: they refuse to give a page the slug `/`. `set_home_page` makes a page the home page. A template with `from` places its pages by its own rule first, and they never become the home page (see [Schemas](https://strife.app/docs/reference/cli/schemas.md#placing-pages-under-a-parent-type)). A document without a URL of its own always goes at the top level. **The home page** | Tool | What it does | | --- | --- | | `set_home_page` | Makes a top-level page the team's home page, the page whose slug is `/`. | `set_home_page` follows the rules of **Set home page** in Studio, and leaves published pages to Studio: * The team doesn't have a home page yet. If it has one, the tool refuses. * The page is at the top level, has a URL, and its template has no `from`. * The page isn't archived and has no scheduled update. * The page isn't published. A published page's address is live, so you make it the home page in Studio. The page's slug becomes `/` in every language it has. In a new team, the assistant creates the home page first and makes it the home page before it creates the other pages, so they go under it. The home page keeps its `/`: `edit_content` and `edit_many` never take it away, just as Studio locks the home page's slug. Its other fields can be edited as usual. **Publish** | Tool | What it does | | --- | --- | | `publish_content` | Publishes up to 25 pages. It shows a preview first, and publishes only once you confirm. | **Share drafts for review** | Tool | What it does | | --- | --- | | `create_snapshot` | Takes a snapshot of a page's draft and returns a link that anyone can read without signing in. | | `list_snapshots` | Lists a page's active snapshot links. | | `revoke_snapshot` | Stops a snapshot link at once. | [Snapshots](https://strife.app/docs/reference/snapshots.md#from-an-mcp-client) describes the three snapshot tools in detail. **Media and alt text** | Tool | What it does | | --- | --- | | `find_assets` | Searches the team's media library: images, videos, audio and files. | | `get_asset` | Returns a file's details, so the assistant can put it in an image or assets field. | | `find_missing_alt_text` | Finds images without alt text, in image fields and in rich text, so the assistant can add it. | **Labels** | Tool | What it does | | --- | --- | | `list_labels` | Lists the team's labels and label groups, with the ids the other tools take. | | `create_label` | Creates a label, optionally in a group, with a color and the areas it is offered in: content, media or both. | | `edit_label` | Changes a label's name, color, areas or group. Pages that use the label keep it. | | `delete_label` | Deletes a label that nothing uses. If pages or media files still carry it, nothing is deleted and the assistant lists them. | | `create_label_group` | Creates a label group. | | `edit_label_group` | Renames a label group. | | `set_label_group` | Moves up to 100 labels into a group, or out of their group. | | `delete_label_group` | Deletes an empty label group. If it still has labels, or a page has it selected in a label group field, nothing is deleted and the assistant lists them. | Label names are unique in a team, so the assistant reuses a label that already exists instead of creating a second one with the same name. A label's color is one of `red`, `orange`, `yellow`, `green`, `teal`, `blue`, `violet` and `pink`, which adapt to light and dark mode, or a hex color such as `#eb5757`. Renaming a group doesn't change its normalized name, so queries on your site that use it keep working. To delete a label that pages use, the assistant first removes it from those pages, and a published page has to be published again. Labels on media files can only be removed in Studio's media library. A label field that its type limits to one label group ([`fields.labels({ group })`](https://strife.app/docs/reference/field-reference/fields.labels.md#limit-the-field-to-one-label-group)) accepts that group's labels: `get_template` lists only those for the field. A draft that puts another label in such a field is still saved, and the assistant gets a warning naming it. A chapters list is written the way it is stored. When the chapters field is localizable, `edit_content` changes the list for the language it is given. When it isn't, the list and the texts in it are shared by every language, so a change in any language changes all of them. A field in a shared list that still holds a value per language, including a language the team has removed, can't be changed in part: `edit_content` refuses and saves nothing, and the assistant sets the whole field instead. See [Languages inside a chapter](https://strife.app/docs/reference/field-reference/fields.chapters.md#languages-inside-a-chapter). The server works with content. It doesn't upload media, which you do in Studio, and it doesn't change templates, which you define in code and deploy with the [CLI](https://strife.app/docs/reference/cli.md). ## How changes reach your site Everything the assistant writes goes into drafts. `create_draft`, `edit_content`, `edit_many` and `add_locale` never touch the published page, so your site keeps showing it while you review the changes in Studio or in the live preview. The exception is `set_home_page`. Like **Set home page** in Studio, it changes the page itself, not a draft. It refuses a published page, so the page is at `/` once it is published. Pages under it that are already published lose its old slug from their addresses at once. Publishing takes two steps. `publish_content` first answers with a preview: the pages that would be published, and any languages that would stay unpublished. The assistant shows you the preview and publishes only after you say yes. Publishing through the server works like publishing in Studio. The assistant acts with your account. Some tools also need you to be a member of the team: * `publish_content`, `discard_draft`, `edit_many` and the snapshot tools need team membership. * `create_snapshot` and `revoke_snapshot` also need edit rights, so a Viewer can list snapshot links but not create or revoke them. * The label tools that make changes need team membership and edit rights. `list_labels` doesn't. * `set_home_page` needs team membership and edit rights. `discard_draft`, `revoke_snapshot`, `delete_label` and `delete_label_group` can't be undone. A snapshot link works for anyone who has it, until it expires after 7 days or is revoked. ## Example prompts Ask the way you would ask a colleague. Name the team if your workspace has more than one. * *Which pages in the Marketing team changed this week?* * *Find our pricing page and summarize what it says about the free plan.* * *Create a draft FAQ item in Marketing that explains how refunds work.* * *Find the blog posts with images that have no alt text, and suggest alt text for each. Write it once I have checked.* * *Add Swedish to the About page and translate it. Don't publish.* * *Share the draft of the launch page with our legal team for review.* * *Publish the three pages we just edited.* * *Create a label group called Colors and move the labels Red, Green and Blue into it.* ## Troubleshooting **"You are not a member of that workspace."** Choose a workspace you belong to on the sign-in page. **"This consent link is no longer valid."** The sign-in page can no longer be used. Start the connection again from your assistant. **The assistant can't find a team.** It may be connected to another workspace. Ask it to list the teams. If the team isn't there, sign the assistant out (in Claude Code, **Clear authentication** in the `/mcp` menu), connect again and choose the right workspace. **Publishing, discarding, snapshots, label changes or setting the home page are refused.** Those tools need you to be a member of the team, and snapshots, label changes and setting the home page also need edit rights. Ask an admin to add you to the team. **A label or label group can't be deleted.** Something still uses it, and the assistant lists what. Remove the label from those pages and media files, or move the labels out of the group, and ask again. --- # Connect Strife to Lovable Source: https://strife.app/docs/tools/connect-strife-to-lovable Use your real content while you build in Lovable: connect the Strife MCP server as a chat connector, turn a page you already published into a new layout, and build against your own templates instead of placeholder data. [Lovable](https://lovable.dev) builds your app from a chat. Connect Strife's MCP server to that chat and it can also see the content you already have: the templates your team writes against, the pages in them, and the words on those pages. That changes what you can ask for. Instead of describing a layout and filling it with placeholder text, you can point at a page you already published and ask for something new built from it — and the components you get back use your real field names, so they still work when they meet real data. > [!NOTE] > A chat connector works while you build. It is personal to you, and it is not part of your published app — your app's visitors never reach Strife through it. See [what this does and doesn't do](https://strife.app/docs/tools/connect-strife-to-lovable.md#what-this-does-and-doesnt-do). ## Connect the MCP server In Lovable, open **Connectors**. The **+** button sits at the top right of the catalog, next to the button that closes it — it is easy to miss. It offers three things: * **Custom connector** — connect an API to your workspace * **MCP server** — connect an MCP to your chat * **MCP registry** — add a directory of MCP servers Choose **MCP server**. Strife is one server: not an API to wire up field by field, and not a directory to browse. Enter `https://mcp.strife.app/mcp` as the URL, keep the default OAuth sign-in, and give it a name such as Strife. Lovable then opens a Strife page in your browser: 1. Sign in to Strife, if you aren't already. 2. Choose the workspace to connect. 3. Check the name under **Details** and choose **Approve**. The assistant then works in the teams of that workspace, with your own permissions. There is no key to copy and no client id to enter — Strife registers the client itself. Each connection covers one workspace. To work in two, add the server twice under different names and approve a different workspace for each. ## Turn a page you already have into a new layout > Find our article about the spring launch in Marketing and build a campaign page from it: the same copy, one hero, three sections and a call to action. The assistant finds the page and reads its fields, then writes the new page from what is actually there. Because the copy is real, the layout meets real sentence lengths, real headings and real image sizes from the first render — which is where placeholder text usually hides the problems. ## Build against your real template > Show me the fields in the Article template, then build a list page for Articles. The assistant asks Strife for the template and gets every field back with an example value. That is what keeps generated code from inventing `post.title` when your field is called `heading`, and it means the component handles what your content really looks like: rich text arrives as HTML, a label field as `"Group/Label"` strings, a reference as the target page's own fields. ## Write content while you build > Create a draft FAQ item in Marketing that explains how refunds work. Everything the assistant writes goes into a draft. Creating, editing, translating — none of it touches a published page, and publishing is a separate step that asks you first. So a prototype can have the content it needs without changing what your site serves today. ## What this does and doesn't do The connector reads and writes **content**. It does not: * **change templates** — your schema is code, deployed with the [CLI](https://strife.app/docs/reference/cli.md) * **upload media** — you add files in Studio; the assistant can find and reuse what is already there * **reach Strife from your published app** — a chat connector works in the Lovable chat, not in the app you ship That last point is worth being precise about. A published Lovable app serves what was built into it; it does not fetch content from Strife while someone is visiting. If you want a site that renders your content and refreshes when you publish, host it where a Node process runs: a Strife site reads from RavenDB with a client certificate, and neither a browser nor a managed edge runtime can present one. [Node.js](https://strife.app/docs/tutorials/getting-started/nodejs.md) and [Astro](https://strife.app/docs/tutorials/astro.md) cover that. ## Troubleshooting **"could not reach registry: registry returned 405."** You picked **MCP registry** instead of **MCP server**. A registry is a directory of servers, so Lovable asks the URL for a list of them; the MCP endpoint only answers JSON-RPC. Start again and choose MCP server. **The assistant can't find a team.** It may be connected to another workspace. Ask it to list the teams. If yours isn't there, sign the connector out, connect again and approve the right workspace. **A change is refused.** Publishing, discarding, snapshots and label changes need you to be a member of the team, and snapshots and label changes also need edit rights. ## The full tool list The [MCP server](https://strife.app/docs/tools/mcp-server.md) page lists all 28 tools, what each one does, and how the same server connects to Claude, Cursor and VS Code. --- # Use the docs from AI tools Source: https://strife.app/docs/how-to-guides/use-the-docs-from-ai-tools Search and read the Strife docs from Claude, Cursor, VS Code and other AI tools: the docs MCP server, llms.txt and every page as markdown. The Strife docs, both the developer docs and the user guide, are made to be read by AI assistants as well as by people. Connect the docs MCP server and your assistant searches the docs and reads the pages it needs to answer. Tools without MCP can use llms.txt or the markdown version of any page. > [!NOTE] > The docs MCP server reads the docs. To let an assistant work with your content, connect the [MCP server](https://strife.app/docs/tools/mcp-server.md). ## Connect the docs MCP server The docs are an MCP server at `https://strife.app/docs/mcp`. It needs no account or key, and it has three read-only tools: * `search_docs` searches the developer docs and the user guide, and returns the best matching sections, each with an excerpt and its address. * `get_page` returns a page as markdown, by its path below `/docs` or its full address. * `list_pages` lists every page with a one-line description. **Claude Code** ```sh claude mcp add --transport http strife-docs https://strife.app/docs/mcp ``` Add `--scope user` to have it in every project, not only the current one. Run `/mcp` in Claude Code to check that it is connected. **Claude** In Claude on the web or in the desktop app, open **Customize → Connectors**, choose **+ Add → Add custom connector** and enter `https://strife.app/docs/mcp` as the URL. The docs need no sign-in. **Cursor** Add the server to `~/.cursor/mcp.json` for every project, or to `.cursor/mcp.json` in one project: ```json { "mcpServers": { "strife-docs": { "url": "https://strife.app/docs/mcp" } } } ``` **VS Code** Add the server to `.vscode/mcp.json` in your project, or run **MCP: Add Server** from the Command Palette: ```json { "servers": { "strife-docs": { "type": "http", "url": "https://strife.app/docs/mcp" } } } ``` Other MCP clients connect the same way: a remote server over Streamable HTTP at `https://strife.app/docs/mcp`. Once it is connected, ask about Strife as you would ask a colleague, for example *How do I define a template with defineType?* or *How do editors restore a snapshot?* Mentioning the Strife docs in the question makes the assistant use them instead of answering from memory. ## llms.txt and llms-full.txt [llms.txt](https://strife.app/docs/llms.txt) lists every page with its description and a link to its markdown version, in the [llms.txt format](https://llmstxt.org). [llms-full.txt](https://strife.app/docs/llms-full.txt) holds every page in full in one file, for tools that take a whole document at once. ## Every page as markdown Add `.md` to the address of any page to get it as markdown, for example [strife.app/docs/reference/cli/schemas.md](https://strife.app/docs/reference/cli/schemas.md). The start page is `readme.md`. The blocks of the docs become standard markdown and every link is a full address, so a page works on its own. The **Copy page** button at the top of each page copies the same markdown, ready to paste into a chat. ## Context7 The docs are also on [Context7](https://context7.com), as the library `/llmstxt/strife_app_llms-full_txt`, for assistants that use Context7's MCP server. --- # Strife technical reference Source: https://strife.app/docs/reference/reference-overview This is the reference part of the documentation. Here you will find the technical details of the SDKs, APIs and configuration options. * SDKs * API * Configuration * Data access * ... --- # SDK overview Source: https://strife.app/docs/reference/sdk-overview --- # Templates Source: https://strife.app/docs/reference/templates Templates in Strife serve as the foundation for creating structured and consistent content. These predefined templates establish the fields, and structure, for all content stored in the database. There are two types of templates in Strife; [Document Templates](https://strife.app/docs/reference/templates.md#document-templates) and [Content Templates](https://strife.app/docs/reference/templates.md#content-templates). ### Document Templates The Document Template serves as template for creating documents in the database. It can incorporate various fields types to meet diverse needs. In addition to defining the fields and structure, there are several other significant aspects of the document template worth exploring. #### Collection The document template specifies the collection name, which is utilized to query the database for all content created using that particular template. This collection name is assigned during template creation and is stored within the metadata section of each document in the database. ```json "@metadata": { "@collection": "Posts", ... } ``` > [!NOTE] > If you are using C#, the collection name is stored alongside the Type property to facilitate model binding and serialization. For how content is bound to your C# models, see [Rendering Content in the .NET guide](https://strife.app/docs/tutorials/getting-started/dotnet.md#4-rendering-content). > [!NOTE] > The Collection plays a crucial role in utilizing and comprehending RavenDB. For a deeper understanding of RavenDB, please explore [additional resources available here](https://strife.app/docs/explanation/ravendb.md). #### Enable URL When creating the document template, you have the option to enable or disable the indexing of content URLs. When enabled, content created from the template is treated as web pages, and a URL is automatically generated and indexed based on the content's slug and hierarchy. This enables easy web access to the content. When disabled, the content is accessible solely by querying the database or referencing from other content. > [!NOTE] > For additional details on the URL indexing, please [refer to this resource](https://strife.app/docs/reference/database/index-url.md). ### Content Templates The Content Template serves as a reusable preset of fields designed for integration within a Document Template or a Chapters field. It's important to note that a Content Template is not meant for creating documents in the database. Instead, any content generated from a Content Template is always stored within the document that uses that particular Content Template. ### Creating templates Templates can be created either through the graphical interface under Settings in Strife Studio, or by [creating and deploying source-controlled JSON templates](https://strife.app/docs/reference/templates/defining-templates-with-json.md). --- # Defining Templates with JSON Source: https://strife.app/docs/reference/templates/defining-templates-with-json Define templates as JSON instead of in Studio's template designer: the template, field and editor properties, with an example. In addition to using the graphical interface in Strife Studio, templates can also be defined using JSON configuration. This allows templates to be stored in source control and automatically synced to Strife as part of your deployment pipeline, depending on your chosen framework and setup. > [!NOTE] > Automatic deployment is included when using the Strife Astro integration `@strifeapp/astro` ### Template Properties | Property | Value | | -------------- | ---------------------------------------------------------------------------------------------- | | displayName | The name of the template displayed in Strife Studio. | | description | A description shown as a hint for editors in Strife Studio. | | collection | The RavenDB collection where documents based on this template will be stored. | | type | Reserved for C# model binding. | | editors | An array defining the fields in the template. See below for details. | | normalizedName | A normalized internal name used for reference in Strife Studio. | | templateType | Defines the template type: `dt` (Document Template) or `ct` (Component Template). | | composable | Boolean indicating if content based on this template can be composed inside other documents. | | filterable | Boolean indicating if this template is offered in the content list's **Collection** filter in Strife Studio. Studio's new interface also offers every template that has a document there, whatever `filterable` says. | | disable URL | Boolean controlling whether content created from this template should have a public URL. | | archived | Boolean indicating if the template is archived. | | icon | The icon name used for display in Strife Studio. See [Icons](https://strife.app/docs/reference/icons.md) for available names. | | allowedOrigins | Optional. Normalized names of the templates whose documents may be this template's origin; absent or a non-empty list, never `[]`. Strife Studio's compose dialog and Set origin then offer only those documents; the API does not validate origins against it. Written by `defineType`'s `from`. | | allowedOriginIds | Optional. Ids of specific documents that may be this template's origin, beside or instead of `allowedOrigins`; absent or a non-empty list, never `[]`. Same Studio-side behaviour, same absence of server-side validation. Written by `defineType`'s `from: { id }`, where the id is read from an environment variable because it differs per workspace. | | baseProperties | `{ "displayName": { "localizable": true/false }, "slug": { "localizable": true/false } }` — whether the document's name and slug have one value per locale (`true`) or one shared value (`false`). Written by `defineType`'s `baseProperties`, which sends only the flags the type states (`{}` when none). An unstated or absent flag is the default: `slug` localizable when the team has two or more locales, `displayName` not. A template saved without `baseProperties` keeps the flags it already has; one saved with it stores exactly what it states, and a flag it leaves out goes back to the default. Readers always get strings, resolved to the requested locale. | | @metadata | RavenDB metadata and model binding information. | > [!NOTE] > **Note:** The `@metadata` property is required for the template to be accepted by Strife and made available inside Strife Studio. ### Field properties | Property | Value | | ----------- | ---------------------------------------------------------------------------------------------------------------------- | | label | The label shown to editors when editing the field. | | description | Optional tooltip text for the field. | | editor | The editor type configuration. See example below and check out [the fields reference](https://strife.app/docs/reference/fields.md) for available types. | | localizable | Boolean indicating if the field should be localizable (available only when localization is enabled). | ### Editor properties | Property | Value | | ------------ | ----------------------------------------------------------------------------------------- | | name | The editor component name. | | type | The editor type. | | propertyName | The property name used in the RavenDB document. | | attributes | Field-specific configuration. See each editor's documentation for supported attributes. | | options | Additional options for the editor. See each editor's documentation for supported options. | > [!NOTE] > You can find specific editor configurations and available options on the respective [Field pages](https://strife.app/docs/reference/fields.md). ### Example ```json { "displayName": "Page", "description": null, "collection": "Pages", "type": null, "editors": [ { "label": "Sections", "description": "", "editor": { "name": "str-chapters", "type": "chapters", "propertyName": "sections", "attributes": { "hint": "

Page sections

" }, "options": { "availableTypes": [ "text", "content", "hero", "bento" ] } }, } ], "templateType": "dt", "normalizedName": "page", "disableURL": false, "archived": false, "icon": "home", "hint": "A demo page", "searchFields": [], "filterFields": [], "composable": true, "filterable": true, "@metadata": { "@collection": "Templates", "Raven-Clr-Type": "Wieldy.Core.Models.Template, Wieldy.Core" } } ``` --- # Global configs Source: https://strife.app/docs/reference/globals Declare site-wide settings such as the navigation or the footer as global configs in strife.config.ts. Editors fill them in from the team menu and your site reads the published values by id. A global config is one document of site-wide settings: the navigation, the footer, the cookie banner, the site's contact details. Each global has a fixed set of fields that you declare in `strife.config.ts`. Editors fill it in from the team menu, with the same draft and publish flow as a page. Your site reads the published values by an id you already know. Before globals, the usual approach was a template plus one content document, and the site kept that document's id in its configuration. A global replaces both: * There is no id to copy between environments. The id comes from the global's name. * Globals are not listed in the content list. * An editor cannot create a second instance or delete the global. ## Declare a global Add a `globals` list to `defineConfig`. Each entry is a `defineGlobal`, and its `fields` take the same `fields.*` builders as [`defineType`](https://strife.app/docs/reference/cli/schemas.md): ```ts title="strife.config.ts" import { defineConfig, defineGlobal, fields, glob } from '@strifeapp/strife/schema'; export default defineConfig({ schema: glob('./src/schemas/**/*.ts'), globals: [ defineGlobal({ name: 'footer', label: 'Footer', icon: 'layout', fields: { heading: fields.text({ label: 'Heading', localizable: true }), description: fields.paragraph({ label: 'Description', localizable: true }), newsletter: fields.toggle({ label: 'Show newsletter sign-up' }), }, }), defineGlobal({ name: 'site-settings', label: 'Site settings', icon: 'settings', fields: { contactEmail: fields.text({ label: 'Contact email' }), }, }), ], }); ``` | Option | Description | | -------- | ----------- | | `name` | Required. The global's identity and part of its id. Lowercase letters, digits and hyphens, starting with a letter, at most 64 characters (`footer`, `site-settings`). `draft`, `scheduled` and `snapshot` are not allowed. | | `label` | Shown in the team menu. Defaults to `name`. | | `icon` | Required. The icon shown next to the global in the team menu. See [Icons](https://strife.app/docs/reference/icons.md). | | `fields` | Required. An object of `fields.*` builders, exactly as in `defineType`. `localizable: true` gives a field one value per locale. | A team can have at most 50 globals. The team menu lists them in the order of the `globals` list. > [!WARNING] > The name is the identity. If you rename a global, you get a new, empty global, and the old one is hidden with its values. Pick names you can keep. ## Push it `strife push` sends the globals to the linked team together with the templates, and lists what changed: ``` ✓ Pushed globals (2 globals) Added globals: footer, site-settings ``` `strife push` checks the list before it sends anything. An invalid name, a reserved name, a duplicate name or more than 50 globals stops the push with a message that names the global, and nothing on the team changes. | Your config | What happens on the team | | ----------- | ------------------------ | | A global is in `globals` | It is added, or its label, icon, order and fields are updated. | | A global is no longer in `globals` | It is hidden from editors. Its values are kept. Push it again and it comes back with them. | | `globals: []` | Every global is hidden. Their values are kept. | | No `globals` key | Globals are left as they are. A push from an older branch or another project does not hide them. | Changing a global's fields works like changing a template's fields. The values of fields that still exist are kept, and the values of removed fields are hidden, not deleted. `strife push --dry-run` prints the globals it would send without changing anything. ## How editors use it Editors open globals from the team's **…** menu, where every global the team has is listed under **Configurations**. A global opens in a full-screen editor with its fields, a status card, and **Discard** and **Publish** at the bottom. * An edit is saved as a draft. Your site does not see it until an editor publishes. * On a team with several locales, the locale switcher and per-locale publish and discard work as they do for pages. * Editing and discarding need the same permission as editing content. Publishing needs the same permission as publishing content. * A global that has never been published opens with empty fields. Globals are edited in the new Strife interface. The classic interface does not list them. ## Read it on your site The published values live in a document with the id `Configurations/globals/`. Load it by id with the store you already use: ```astro title="src/layouts/Layout.astro" --- import { store } from 'strife:store'; type Footer = { heading?: Record; description?: Record; newsletter?: boolean; }; const locale = Astro.currentLocale ?? 'en'; const session = store.openSession(); const footer = await session.load