Community编程与开发github.com

集成 Croct SDK

在应用程序中集成 Croct SDK,用于渲染插槽内容、评估 CQL 查询以及识别用户。

集成 Croct SDK 是什么?

该技能为用户提供在多种技术栈中集成 Croct SDK 的完整指南,包括 JavaScript、React、Next.js、Vue、Nuxt、Shopify Hydrogen 以及 PHP 框架(如 Laravel、Symfony、Drupal)。它指导用户完成从选择适当的 SDK 和安装(通过 CLI 或手动)到添加和渲染内容插槽的整个过程。该技能还涵盖了核心概念,如插槽 ID 和版本管理、回退和默认内容处理、客户端与服务器端渲染策略、CQL 查询评估、身份标识管理与用户匿名化。此外,它提供了详细的错误处理指南和常见陷阱的修复方法,确保开发者能够有效地部署和调试 Croct 集成。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/croct-tech/agent-skills/tree/HEAD/skills/croct-integrate-sdk

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

集成 Croct SDK 是做什么的?

将 Croct SDK 接入应用程序,使其能够渲染插槽内容、评估 CQL 并识别用户。内容和受众存在于 Croct 仪表板中;代码仅通过 ID 和版本引用插槽,并提供回退内容。

工作流程

- [ ] 1. 检测技术栈并选择 SDK(见下表)
- [ ] 2. 使用 CLI 安装(`croct init`,由用户运行),仅在用户要求或 CLI 无法运行时手动安装
- [ ] 3. 使用 CLI 添加插槽(`npx croct@latest add slot home-hero@1 --example`)以生成类型 + 回退内容
- [ ] 4. 渲染插槽:框架支持时在服务器端渲染,否则在客户端渲染
- [ ] 5. 在登录/注销时识别/匿名化用户(或在初始化时传递用户 ID)
- [ ] 6. 验证:集成页面显示“过去 24 小时内收到流量”;否则启用调试模式

1. 选择 SDK

首先读取 package.json / composer.json。为框架选择最具体的 SDK;切勿在 React、Next.js、Vue、Nuxt 或 Hydrogen 内部使用纯 JavaScript SDK。

技术栈包名初始化方式服务器端渲染参考文档
纯 JS、任何打包工具或 <script> 标签@croct/plug(或 https://cdn.croct.io/js/v1/lib/plug.js)启动时调用一次 croct.plug({appId})使用 @croct/plug/api 中的 apiKey 配合独立的 fetchContent/evaluatejavascript.md
React(SPA、Vite、任何非 Next 的 SSR)@croct/plug-react在根节点使用 <CroctProvider appId="...">客户端 Hook 需要 initial;低层使用 @croct/plug-react/apireact.md
Next.js(App Router 或 Pages Router)@croct/plug-next中间件(≤15)/ 代理(≥16)+ @croct/plug-next/CroctProvider 提供的 <CroctProvider>是:使用 @croct/plug-next/servernextjs.md
Vue@croct/plug-vueapp.use(createCroct({appId}))组合式 API/组件;SSR 需要初始值vue.md
Nuxt@croct/plug-nuxt在 nuxt.config 中配置 modules: ['@croct/plug-nuxt']是nuxt.md
Shopify Hydrogen(React Router 7 或 Remix)@croct/plug-hydrogenVite 插件 + 从 @croct/plug-hydrogen/server 导入 createCroctMiddleware / createCroctContext是hydrogen.md
纯 PHPcroct/plug-php(+ 一个 PSR-18 客户端,例如 guzzlehttp/guzzle nyholm/psr7)Croct::fromDotenv(),然后在输出前调用 Croct::emitCookies()是(服务器优先)php.md
Laravelcroct/plug-laravel.env 凭据是laravel.md
Symfonycroct/plug-symfony symfony/twig-bundle在 config/bundles.php 中注册 Bundle + .env 凭据是(Twig)symfony.md
Drupalcroct/plug-drupal启用模块;凭据配置在 settings.php 中;重建缓存是drupal.md
Storyblok(JS 或 PHP)—使用 croct-integrate-platforms 技能——
不支持的语言或原始 HTTP—使用 croct-use-api 技能——

2. 安装

每个 SDK 的集成页面(包括 PHP、Laravel、Symfony、Drupal 和 Hydrogen)都推荐使用 CLI。init 是交互式的,需要登录会话,因此请要求用户在项目根目录的自己的终端中运行:

npx croct@latest init

croct init 会检测框架、登录、选择组织/工作空间/应用程序、安装匹配的 SDK 并配置设置(Provider、中间件、环境变量)。当用户已有会话并知道 ID 时,你可以自己运行非交互式形式: npx croct@latest --no-interaction init --sdk next --org <org> --wor <workspace> --dev-app <dev-app> --prod-app <prod-app> (--sdk 仅接受 javascript、react、vue、next、nuxt;省略则自动检测)。标志、CI 使用和 croct.json 存在于 croct-use-cli 技能中。仅在用户要求或 CLI 无法运行时,才回退到框架参考文件中的手动步骤。

3. 添加插槽

始终传递插槽 ID 和版本。如果不传递,CLI 会提示输入插槽,而你无法回答:

npx croct@latest add slot home-hero@1 --example

这会生成 TypeScript 类型(因此 useContent('home-hero@1') / fetchContent('home-hero@1') 是有类型的),下载插槽的默认内容作为自动回退,并编写一个工作示例。仪表板更改后,重新运行 croct install / croct update 以重新同步(参见 croct-use-cli)。

核心概念(所有 SDK)

插槽 ID 和版本

  • 将插槽引用为 <id>@<version>,例如 home-hero@1。无版本(home-hero)表示 home-hero@latest。
  • 始终固定版本。 未固定的插槽会立即接收破坏性 schema 更改。当仪表板创建新的主版本时,应用程序会继续接收旧版本,直到代码被更新。
  • 使用 SlotContent<'home-hero@1'> 和 ComponentContent<'card@1'> 对内容进行类型化(由 @croct/plug、@croct/plug-react、@croct/plug-next 导出)。联合插槽解析为 _type 上的可区分联合。

回退、默认和初始内容

术语说明来源
默认内容当没有体验匹配、区域设置无内容、请求静态内容或检索失败时显示的插槽内容仪表板
回退请求失败时渲染的值代码中的 fallback 选项,否则为 CLI 下载的默认内容(@croct/content)
初始内容(React/Next 客户端 Hook)SSR/预渲染期间以及客户端加载时渲染的值initial 选项;CLI 会自动添加

SDK 中的解析顺序:动态内容 → 显式 fallback → CLI 默认内容 → 错误。如果没有回退且没有 CLI 内容,失败的 fetch 会抛出异常(JS croct.fetch 拒绝)。直接从 @croct/content 使用 getSlotContent(slotId, locale?) / loadSlotContent(slotId, locale?) 读取 CLI 内容(推荐使用支持代码分割的异步版本)。

客户端与服务器端渲染

需求操作
第一 HTML 中包含最终内容,无闪烁,可爬取在服务器端获取(Next fetchContent 来自 @croct/plug-next/server、Nuxt、Hydrogen、PHP 系列)
页面必须保持为静态文件 / CDN / output: 'export'使用带有 initial 值的客户端 Hook/组件或 <Suspense> 边界
视口下方部分,骨架屏可接受客户端渲染即可
纯 React / 自定义 SSR 中的服务器端渲染使用 @croct/plug-react/api(或 @croct/plug/api)中的 fetchContent / evaluate(带有 apiKey),然后将内容作为 props 传递

服务器端请求使用 API 密钥 进行身份验证(切勿将其发送到浏览器);客户端请求使用应用程序 ID。将 appId 和 apiKey 都传递给独立函数是错误的。

查询评估

使用 croct.evaluate(query, {attributes})(JS)、useEvaluation / <Personalization>(React/Next 客户端)或 evaluate / cql`...`(Next 服务器)在运行时评估 CQL。查询长度限制为 500 个字符;结果可以是任何 JSON('location' 返回一个对象)。始终提供回退(.catch(() => false) 或 fallback: false)。CQL 语法:croct-cql 技能。

评估还是插槽?文档将插槽视为无需代码更改即可更新内容的方式;而评估的查询存在于代码中,仅通过部署更改。

需求使用
营销人员可以更改、安排或 A/B 测试的内容、受众或发布插槽加体验(参见 croct-personalize-and-test)
由工程团队固定的逻辑(显示/隐藏小部件、根据条件分支),没有可编辑的内容evaluate / useEvaluation 加上回退

上下文属性

将应用程序特定数据(计划、购物车状态)作为 attributes(JS/React)或 context.attributes(Next 服务器、独立函数)传递;在 CQL 中读取为 context's plan is "premium"。限制:最多 30 个条目,5 层深度,键 ≤ 50 字符,字符串值 ≤ 50 字符。

凭据和环境变量

技术栈应用 IDAPI 密钥
Next.jsNEXT_PUBLIC_CROCT_APP_IDCROCT_API_KEY
NuxtNUXT_PUBLIC_CROCT_APP_IDNUXT_CROCT_API_KEY
HydrogenPUBLIC_CROCT_APP_IDCROCT_API_KEY
PHP、Laravel、SymfonyCROCT_APP_IDCROCT_API_KEY
Drupal$settings['croct.app_id']$settings['croct.api_key']
JavaScript、React、VueappId 选项 / prop仅用于服务器端独立函数
  • 在应用程序的集成页面上找到应用 ID;在其 API 密钥页面上创建密钥。
  • 对于颁发用户令牌的服务器端 SDK(Next.js),API 密钥需要颁发用户令牌权限。
  • 每个环境都有自己的应用程序。在 localhost 上使用生产应用 ID(反之亦然)会导致凭据无效错误。

身份识别和匿名化

  • 在登录/注册时调用 identify(userId),在注销时调用 anonymize()。身份更改会结束当前会话并开始新会话。
  • 如果用户在页面加载时已登录,则在初始化时传递 ID(croct.plug 中的 userId / <CroctProvider>),以便 SDK 不会创建额外的匿名会话。
  • userId 必须是字符串;转换数字 ID(最好在服务器端)。优先使用随机 ID(UUID v4)而不是电子邮件或序列号。
  • 当应用程序设置中启用了需要签名令牌时,userId/identify(未签名令牌)会失败;改为传递签名的 token。Next.js 使用 CROCT_API_KEY 自动签名令牌。
  • Next.js:优先在中间件/代理中使用 withCroct({userIdResolver}),以在每个请求中使令牌与认证会话保持同步。

值得了解的 Plug 选项

appId、debug、test、track(自动跟踪,默认 true)、userId / token(互斥)、tokenScope(global | isolated | contextual)、defaultFetchTimeout(JS/React 为 5000ms;Next 为 2000ms)、defaultPreferredLocale、baseEndpointUrl(模拟服务器)、cookie(将客户端 ID / 用户令牌 / 预览令牌存储在第一方 Cookie 中)、eventMetadata、urlSanitizer、logger。完整列表:javascript.md。

跟踪和数据收集

使用 croct.track('goalCompleted', {goalId}) 跟踪目标;使用 croct.user.edit().set(...).save() / croct.session.edit() 编辑用户画像/会话。事件目录、推荐事件和属性规则:croct-track-events 技能。

常见陷阱

正确做法:

  • 固定插槽版本(home-hero@1)并保留回退(CLI 默认内容或显式回退)。
  • 为每个可能在服务器端渲染的客户端 useContent/useEvaluation 提供 initial(或 <Suspense>)。
  • 仅在 useEffect 或事件处理程序中调用客户端专属的 Plug 方法(useCroct().track、identify、user.edit),切勿在渲染期间调用。
  • 将加载 SDK 的每个域名添加到应用程序的可信源中。
  • 出现问题时首先启用调试模式(debug: true、NEXT_PUBLIC_CROCT_DEBUG=true),然后检查 Network 标签页。

错误做法:

  • 调用 croct.plug 两次(先调用 unplug())或在 plug 之前调用任何方法(“Croct is not plugged in”)。
  • 将 API 密钥放在客户端代码或 NEXT_PUBLIC_* 变量中。
  • 同时在 <script> 标签的 ?appId= 和 plug 中指定应用 ID(会导致应用 ID 冲突错误)。
  • 在希望保持静态的路由上调用 Next 的 fetchContent;这会将该路由标记为动态渲染。请在那里使用客户端 Hook。
  • 在 Next.js App Router 外部使用 cql 标签;请使用带 route 参数的 evaluate。

常见错误

错误修复方法
Croct is not plugged in.在启动时调用 croct.plug,然后再进行其他调用
The app ID must be specified when it cannot be auto-detected.传递 appId(或在 <script> 标签上使用 ?appId=)
The request was not authorized, most likely due to invalid credentials.应用 ID 错误、环境错误、令牌过期/被篡改(清除 Cookie 和本地存储),或启用了“需要签名令牌”时使用了未签名令牌
CORS 错误 / The origin of the request is not allowed in your application settings.将域名添加到可信源
The user ID must be a string.将 ID 转换为字符串
The request timed out.增加 timeout / 默认超时时间;在调试日志中检查 X-Croct-Timing / X-Croct-Region
The query is too complex.查询超过 500 字符;简化、拆分或通过属性传递数据
The service is temporarily suspended.非代码错误:工作空间被暂停或检测到机器人流量(X-Suspension-Reason);保留回退
The application has exceeded the monthly active users (MAU) quota.升级计划或等待下一个周期
useCroct() can only be used in the context of a <CroctProvider> component.将组件树包裹在 <CroctProvider> 中
The initial content/value is required for server-side rendering (SSR).添加 initial,或在服务器端获取
Did you forget to configure Croct's middleware?添加 Next.js 中间件/代理
someFunction() requires specifying the route parameter outside app routes.传递 route: context(Pages Router/API 路由)
Did you forget to set the SOME_ENV_VAR environment variable?设置 NEXT_PUBLIC_CROCT_APP_ID / CROCT_API_KEY
发布后内容未更新(无错误)客户端 Hook 在 expiration(60 秒,每次渲染后延长)内缓存结果;更改 cacheKey 以强制重新获取。检查更改是否已发布,而非草稿。固定版本(home-hero@1)永远不会获取新主版本:运行 croct upgrade。请求失败后回退内容过时:croct update 刷新 CLI 默认内容

参考文档索引

仅加载正在使用的技术栈对应的文件。

  • references/javascript.md — @croct/plug:插件选项、fetch、evaluate、test、身份标识、补丁、独立的 @croct/plug/api、测试、错误。
  • references/react.md — @croct/plug-react:Provider、useContent、<Slot>、useEvaluation、<Personalization>、useCroct、SSR 初始值、测试。

Individual skills in this repo

This repo contains 4 individual skills — each has its own dedicated page.

croct-tech/agent-skills

>- Use when writing, reading, reviewing, or debugging Croct's Contextual Query Language (CQL): audience criteria, `croct.evaluate()` / `useEvaluation` / `<Personalization query>` / Next.js `cql` tag queries, Evaluation API `query` bodies (`/client/web/evaluate`, `/external/web/evaluate`), and dynamic content values (`"type": "dynamic"`, `"expression"`). Covers context variables (user, session, page, location, campaign, cart, device, browser, context, now/today), data types and conversions, accessors and selectors (`'s`, `property X of`, `[1st]`, `[*]`, `[...]`), tests (`is`, `matches`, `is like`, `contains either`, `is between`, `is defined`, `is returning`), quantifiers (`some ... satisfies`), macros, modifiers, event expressions (`user has viewed a page`, `user has abandoned a cart`, `user has completed goal`), audience estimation, and recipes. Triggers: "write an audience", "target mobile users in New York", "CQL syntax error", "audience never matches", "unavailable estimate".

croct-tech/agent-skills

>- Use when connecting Croct to a third-party platform or migrating to Croct from another personalization or experimentation tool. Covers Storyblok (Optimize by Croct app, @croct/plug-storyblok, Storyblok withCroct, resolveContent, croct/plug-storyblok, CroctStoriesApi), Sanity and Strapi (slot fallback, dynamic zones, metadata.contentSource), Shopify Hydrogen storefront events, Shopify custom pixel (croctPixel, PUBLIC_CROCT_SHOPIFY_PIXEL, checkout and order tracking), VTEX, Google Tag Manager data layer, Microsoft Clarity tags, HubSpot forms (hbspt.forms.create, hs-form-event), firmographic providers 6sense, Demandbase, Clearbit Reveal, and ZoomInfo WebSights (firmographics attributes, account-based audiences in CQL), and migrations from Mutiny and Ninetailed (Experience component, Contentful sunset). Triggers include cdn.croct.io/plug-integration scripts, "personalize Storyblok blocks", "track Shopify checkout", "send VTEX events", "ABM personalization", "replace Mutiny".

croct-tech/agent-skills

>- Use when designing or changing Croct content models: regular vs union components, what becomes a component, slot, structure, or primitive attribute; writing component schema JSON (`structure`, `union`, `reference`, `text`, `number`, `boolean`, `list`, `@croct/file`, `@croct/richText` rich text, `format`, `choices`, `optional`, `private`, `position`); writing content definition JSON (`static`/`dynamic` values, `nullable`, `default`, `{{placeholder}}` paths); slot default, localized, experience, experiment, or content group content; schema limit errors (30 attributes, 6 nesting levels, 10 union members, complexity score 50); component versioning and breaking changes (`home-hero@2`); refactoring (duplicate and modify, duplicate and replace, flatten and merge); Markdown in text attributes with `@croct/md-lite`. Phrasings: "model content for a hero", "add an attribute to the banner component", "support variations", "component is too complex", "localize the hero", "translations", `preferredLocale`.

croct-tech/agent-skills

>- Use when planning or implementing personalization or A/B testing with Croct: creating an experience (audience, slots, content, priority, scheduling, drafts), adding an experiment (A/B/n, primary goal ID, traffic allocation, variants, cross-device consistency), wiring the code it needs (slots, `croct.track('goalCompleted', {goalId})`, `orderPlaced`, `leadGenerated`, `userSignedUp`), server-side feature-flag experiments, redirect experiments, personalization recipes (UTM campaigns, ABM, search terms, location, free shipping, interests, blog readers, leads, customers, organic intent, HubSpot forms), or reading the experience, experiment, application, or workspace dashboards (probability to be best, potential loss, "Experiment in progress", "Recommended winner", "No clear winner", "Track your goal"). Phrasings: "personalize the hero for LinkedIn visitors", "A/B test this CTA", "which variant won?", "why does my experiment show no conversions?".

相关技能