Community程式設計與開發github.com

整合 Croct SDK

在應用程式中安裝並使用 Croct SDK:渲染區塊內容、評估 CQL 查詢、伺服器端或客戶端擷取、預渲染、識別使用者、管理應用程式 ID / API 金鑰環境變數、測試或除錯。涵蓋 JavaScript、React、Next.js、Vue、Nuxt、Shopify Hydrogen、PHP、Laravel、Symfony 和 Drupal。

整合 Croct SDK 是什麼?

此技能引導開發者在各種前端和後端框架中整合 Croct SDK,以管理個人化內容和 A/B 測試。它涵蓋 JavaScript、React、Next.js、Vue、Nuxt、Shopify Hydrogen、PHP、Laravel、Symfony 和 Drupal 等平台。核心功能包括透過插槽 ID 渲染內容、評估 CQL 查詢、管理使用者識別與匿名化,以及處理伺服器端與客戶端渲染。技能詳細說明了依賴 CLI 的安裝和插槽新增流程、區塊版本釘選以確保穩定性、內容回退與載入策略,以及常見錯誤的解決方案。

相容平台~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 的獨立 fetchContent/evaluate,需提供 apiKeyjavascript.md
React(SPA、Vite、任何非 Next 的 SSR)@croct/plug-react在根層級包裹 <CroctProvider appId="...">客戶端鉤子需要 initial;低階 API 使用 @croct/plug-react/apireact.md
Next.js(App 或 Pages Router)@croct/plug-nextmiddleware(≤15)/ proxy(≥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,並設定相關配置(提供者、中介軟體、環境變數)。當使用者已有工作階段且知道 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。
  • **始終鎖定版本。**未鎖定的插槽會立即套用破壞性架構變更。當儀表板建立新的主要版本時,應用程式會繼續接收舊版本,直到程式碼更新。
  • 使用 SlotContent<'home-hero@1'> 和 ComponentContent<'card@1'>(由 @croct/plug、@croct/plug-react、@croct/plug-next 匯出)來定義內容型別。聯合插槽會解析為 _type 上的鑑別聯合。

備用內容、預設內容和初始內容

術語說明來源
預設內容當沒有符合的體驗、沒有對應地區、請求靜態內容或擷取失敗時顯示的插槽內容儀表板
備用內容請求失敗時渲染的值程式碼中的 fallback 選項,否則為 CLI 下載的預設內容(@croct/content)
初始內容(React/Next 客戶端鉤子)SSR/預渲染期間和客戶端載入時渲染的值initial 選項;CLI 會自動新增

SDK 中的解析順序:動態內容 → 明確的 fallback → CLI 預設內容 → 錯誤。如果沒有備用內容且沒有 CLI 內容,則失敗的擷取會拋出錯誤(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 值或 <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:建議在 middleware/proxy 中使用 withCroct({userIdResolver}),以在每次請求時保持權杖與驗證工作階段的同步。

值得了解的 Plug 選項

appId、debug、test、track(自動追蹤,預設為 true)、userId / token(互斥)、tokenScope(global | isolated | contextual)、defaultFetchTimeout(JS/React 為 5000 毫秒;Next 為 2000 毫秒)、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>)。
  • 僅在客戶端呼叫 Plug 方法(useCroct().track、identify、user.edit),需在 useEffect 或事件處理常式中進行,切勿在渲染期間呼叫。
  • 將所有載入 SDK 的網域新增到應用程式的信任來源。
  • 遇到問題時先開啟除錯模式(debug: true、NEXT_PUBLIC_CROCT_DEBUG=true),然後檢查 Network 標籤。

禁止事項:

  • 呼叫 croct.plug 兩次(應先呼叫 unplug())或在 plug 之前呼叫任何方法(「Croct 尚未插入」)。
  • 將 API 金鑰放在客戶端程式碼或 NEXT_PUBLIC_* 變數中。
  • 同時在 script 標籤的 ?appId= 和 plug 中指定應用程式 ID(會產生衝突的應用程式 ID 錯誤)。
  • 在希望保持靜態的路由上呼叫 Next 的 fetchContent;這會使該路由變成動態渲染。請改用客戶端鉤子。
  • 在 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 中介軟體/代理
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
發布後內容未更新(無錯誤)客戶端鉤子會快取 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:提供者、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?".

相關技能