TengenceTengence
Product docs

Search Widget Integration

Embed Tengence Search's search box and result list on your own site: script and npm setup, token backend contract, prop reference, and common issues.

The Search Widget puts Tengence Search’s search box and result list directly into your own site — no hand-written query calls, pagination, or loading states. It ships as @tengence/tengence-widget-sdk and can be loaded either with a single <script> tag or as an npm package in your build.

Typical uses: add search to a marketing site or blog; replace a store’s search box on listing pages; drop a result block onto a campaign landing page without rebuilding the whole front end.

What you get

  • A search box with input suggestions, hot queries, and keyboard navigation
  • A result list with pagination, page-size selector, loading and empty states
  • Built-in UI copy in English, Simplified Chinese, and Traditional Chinese, with per-key overrides
  • Tokens issued by your own backend, so the API Key never reaches the browser

Before you start

  1. A search app exists in the console, and you have its App ID and API Key (Tengence Search → Apps → detail).
  2. The app is bound to a dataset with a configured index and returns results for at least one query.
  3. Your site can reach the search API (default https://api.tengence.com) and CORS is allowed; if you front it with your own proxy, point baseURL there.

Option 1: a single script tag

Best for static sites, WordPress, or any page where you can edit the template. The SDK registers two custom elements, tg-search-box and tg-search-result, and renders them through methods on window.tengence.

<!-- Containers first, wherever you want them -->
<div id="tg-box"></div>
<div id="tg-result"></div>

<script>
  var s = document.createElement("script");
  s.src = "https://static.tengence.com/widget/tengence-widget-sdk@1.0.8.js";
  s.onload = function () {
    // 1) Where the widget exchanges for a token: your own backend, never Tengence's issue endpoint
    window.tengence.setAccessTokenUrl("https://your-site.com/api/tg-token");

    // 2) Optional UI language (BCP-47). Falls back to <html lang>, then en.
    window.tengence.setLocale("en");

    // 3) Render
    window.tengence.renderSearchBox("tg-box", {
      searchPageUrl: "/search",   // where Enter takes the user
      queryKey: "q"               // query parameter name; empty means no parameter
    });

    window.tengence.renderSearchResult("tg-result", {
      pageSize: 10,
      pageSizeOptions: [5, 10, 20, 50]
    });
  };
  var first = document.getElementsByTagName("script")[0];
  first.parentNode.insertBefore(s, first);
</script>

Pin the version in src; don’t use @latest. Upgrades change behavior and styling. The CDN and npm versions are not always in lockstep, so check the current release before you pick a number.

Option 2: npm package

npm install @tengence/tengence-widget-sdk
// Import once in your entry file; this registers the custom elements.
import "@tengence/tengence-widget-sdk";

window.tengence.setAccessTokenUrl("https://your-site.com/api/tg-token");
window.tengence.setLocale("en");

window.tengence.renderSearchBox("tg-box", { searchPageUrl: "/search", queryKey: "q" });
window.tengence.renderSearchResult("tg-result", { pageSize: 10 });

In Vue or React, put the container id in the template and call renderSearchBox / renderSearchResult from onMounted / useEffect. Calling before the container exists only logs an error — nothing renders.

Initialization and credentials

The widget never embeds an API Key. Whenever it needs a request, it POSTs to your tokenURL, reads accessToken from the response, caches it in localStorage, and fetches a new one on expiry or a 401.

Token endpoint contract

  • Method: POST, no body by default (JSON body only when tokenBody is set)
  • Expected response:
{
  "code": "SUCCESS",
  "data": {
    "accessToken": "xxxxx",
    "accessExpAt": 1767225600000
  }
}

accessExpAt is a millisecond timestamp and is optional; without it the widget skips local expiry and relies on 401 to refresh. If accessToken comes back as a JSON string, the widget extracts the inner token automatically.

What your backend does

Exchange the API Key for a token at Tengence’s issue endpoint and pass the token to the browser. The API Key stays server-side — never in page source or a front-end env var.

// your /api/tg-token (Node example)
export default async function handler(req, res) {
  const r = await fetch("https://api.tengence.com/v1/app/auth/token/issue", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ apiKey: process.env.TG_API_KEY }),
  });
  const json = await r.json();
  res.setHeader("Cache-Control", "no-store");
  res.status(200).json(json); // pass code/data through as-is
}

Init API

window.tengence.init({ ... }) is the fuller form, useful when you need custom headers:

Param Type Description
tokenURL string Token endpoint, required
getHeader () => Record Headers sent with each token request, e.g. a custom auth header
baseURL string Search API root, default https://api.tengence.com
tokenBody object JSON body sent with the token request, e.g. { module: "search" }
locale / lang string Global UI language

Calling init again with the same config reuses the cached token; a config change clears it and fetches a new one.

Rendering the search box

window.tengence.renderSearchBox("tg-box", {
  searchPageUrl: "/search",
  queryKey: "q",
  emptyText: "No matching suggestions",
  locale: "en",
});
Param Type Default Description
emptyText string built-in copy Text when there are no suggestions
searchPageUrl string empty Page to navigate to on Enter/click; empty keeps the query on the current page
queryKey string empty URL parameter name for the query; empty means no parameter
language string empty Content language filter, e.g. en, zh-hans, zh-hant; also a UI-language fallback
languageFilterEnabled boolean false Filter results by language
locale / lang string global UI language, BCP-47
messages object empty Per-key UI copy overrides
onNavigate function empty Take over navigation; receives { url, query }. Fires only when searchPageUrl is set and the target differs from the current page

searchPageUrl and queryKey can also live on the container as data-search-page-url and data-query-key.

If the container already holds a tg-search-box, repeat calls only update config — the input and whatever the user typed are preserved.

Rendering the result list

window.tengence.renderSearchResult("tg-result", {
  pageSize: 10,
  pageSizeOptions: [5, 10, 20, 50],
  emptyText: "No results found",
  loadingText: "Searching…",
});
Param Type Default Description
pageSize number component default Rows per page
pageSizeOptions number[] [5,10,20,50] Page-size choices
emptyText string built-in copy Empty-state text
loadingText string built-in copy Loading text
language / languageFilterEnabled string / boolean empty / false Same as the search box
locale / lang / messages as above UI language and copy overrides

The result list reads its query from the page URL using queryKey (for example ?q=headphones). So the box that navigates and the list that reads the parameter must share one queryKey; otherwise the result page searches for nothing.

Unlike the search box, the result list clears and rebuilds its container on every render — repeat calls lose pagination state.

Language and copy

  • UI language: setLocale("en") globally, or locale per component. With neither, it follows <html lang>, then falls back to en.
  • Content filter: language plus languageFilterEnabled: true limits results to one content language. Off by default.
  • Copy: addMessages overrides globally; messages applies to one component only.
window.tengence.addMessages("en", {
  searchBox: { emptySuggestion: "Try another term" },
});

Pass only the keys you want to change; the rest fall back to the bundled language pack.

Troubleshooting

Container stays empty
renderSearchBox / renderSearchResult ran before the container existed. Call after DOMContentLoaded, onMounted, or useEffect, and double-check the id.

Result page finds nothing
The box’s queryKey and the page’s parameter don’t match, or searchPageUrl was never set so no navigation happened. Use the same key in both places, e.g. q.

401s or an endless spinner
Your token endpoint isn’t returning code: "SUCCESS" with data.accessToken. Curl it directly and inspect the shape; then confirm the API Key belongs to this app and the app’s service is active.

CORS errors
Either baseURL or tokenURL is cross-origin without CORS. Hosting the token endpoint on your own domain is the simplest fix; for the search API, verify Access-Control-Allow-Origin is present.

Site CSS leaks into the widget
The widget renders as custom elements, but host-page globals (a * { box-sizing } reset, global input styles) can still bleed in. Scope your resets or wrap the container in a namespaced class.

Strict CSP
Allow https://static.tengence.com (script-src) and the search API domain (connect-src). With the npm route, only the API domain is needed.

Versions and upgrades

  • Package: @tengence/tengence-widget-sdk, currently 1.2.x.
  • Script route: bump the version in src. npm route: upgrade and rebuild.
  • Before production, verify three things on staging: box navigation, result pagination, and language switching.
On this page