# AutoSugges — Add AutoSugges autocomplete to a plain HTML page

## How do I add autocomplete to a plain HTML page?

Add data-autosugges-key and data-autosugges-base-url attributes to any element, then load the browser build from /sdk/v1/autosugges.js. Loading the script mounts an accessible autocomplete inside a shadow root, so host page styles cannot interfere. No bundler, framework or hand-written combobox markup is required.

You are integrating AutoSugges, a hosted autocomplete and list-of-values service. Everything you need is in this message; do not guess at anything it does not state, and do not fetch documentation to fill a gap — ask instead.

## Objective
A working autocomplete on a plain HTML page, rendered inside a shadow root so it cannot collide with the host page’s styles, with no combobox markup written by hand.

## Environment
- Target framework/runtime: JavaScript (no framework).
- SDK package: `@autosugges/client` (version 0.1.1).
- Runtime HTTP API version: `v1`.
- Install: No install step. Load the prebuilt browser build with a <script> tag: <script src="YOUR_AUTOSUGGES_WEB_ORIGIN/sdk/v1/autosugges.js"></script>, or from the jsDelivr CDN: https://cdn.jsdelivr.net/npm/@autosugges/client/dist/browser/autosugges.js. For a pinned build use the immutable `/sdk/v1/autosugges.<hash>.js`; `/sdk/v1/autosugges.js` always resolves to the current v1 build.

## Prerequisites
- An AutoSugges list that has been published at least once. An unpublished list has nothing to serve yet and returns `list_not_published`.
- The publishable key issued for the application that will query it.
- The runtime base URL for the environment you are targeting. AutoSugges does not have one fixed public hostname baked into the SDK — the dashboard's integration panel shows the origin for your environment.
- The AutoSugges web app's own origin, to load /sdk/v1/autosugges.js from — the dashboard's integration panel shows it. No bundler required.

## Values you must supply
- `baseUrl` (required, public by design) — placeholder `YOUR_RUNTIME_BASE_URL`. The origin of the AutoSugges runtime — scheme and host, no trailing slash and no path. The SDK appends `/v1/...` itself. Source: The AutoSugges dashboard's integration panel, for the environment you are deploying to.
- `publishableKey` (required, public by design) — placeholder `YOUR_PUBLISHABLE_KEY`. Identifies the consumer, the application, the subscription, the canonical list and the query policy in a single server-side lookup. The client never supplies a list id, tenant id or version hash — if a generated integration is passing one of those, it is wrong. Source: The AutoSugges dashboard, under the application that will make the queries.
- `accessToken` (optional, SECRET — server-side only) — placeholder `YOUR_SERVER_MINTED_ACCESS_TOKEN`. Only for a list whose policy requires a token. Short-lived, sent as `authorization: Bearer <token>`, and never minted, stored or hardcoded in client code. Source: Your own backend, which mints it from your AutoSugges credentials.
- The base URL below is still the literal placeholder `YOUR_RUNTIME_BASE_URL`. Ask the developer for their environment's runtime origin and substitute it; do not invent an autosugges.com hostname.

## Request contract
The publishable key travels as a query parameter (or, for selection reports, a JSON body field) — NOT as an Authorization header. The Authorization header is reserved for the optional access token of a protected list.
- `GET /v1/bootstrap?key=<publishable key>` — Resolves the list identity, the active version hash and the effective query policy for this key. Call once per session before querying. Key placement: `key` query parameter. Headers: `x-request-id`: a per-request correlation id (the SDK mints one automatically); `authorization: Bearer <access token>`: optional, and only for a list whose policy requires a token.
- `GET /v1/query?key=<publishable key>&q=<text>&locale=<optional BCP-47 tag>` — Returns the pre-ranked suggestions for one query. Key placement: `key` query parameter. Headers: `x-request-id`: a per-request correlation id; `authorization: Bearer <access token>`: optional, as above.
- `POST /v1/selection` — Reports which suggestion the user chose, so ranking can improve. Optional: skipping it degrades ranking quality and nothing else. Key placement: `key` field of the JSON body, alongside `selectionId`, `queryRequestId`, `listId`, `itemId`, `query` and `position`. Headers: `content-type: application/json`; `x-request-id`.

## Policy that arrives from bootstrap — never hardcode these
- `requestId` (string) — Correlation id for this bootstrap call.
- `list.id` (string (UUID)) — The canonical list this key resolves to. Never supplied by the client.
- `activeVersionHash` (string) — The published version currently serving. Compare it to a stored hash to decide whether a cached local copy is stale.
- `queryPolicy.minQueryChars` (number) — Minimum characters before a query is legal. Never below 2, and never hardcoded — a shorter query is rejected and not billed.
- `queryPolicy.debounceMs` (number) — How long to wait after the last keystroke before issuing a query.
- `queryPolicy.defaultResultLimit` (number) — How many suggestions a list returns by default. Informational: the server already returns its ranked set, so the client does not send this back.
- `queryPolicy.rememberLastSelection` (boolean) — Tenant policy for prefilling a previously chosen item. Treat anything other than literal `true` as off.

## What one suggestion looks like
- `itemId` (string) — Stable identifier. Use it as the React/list key.
- `value` (string) — The canonical value — what you store.
- `displayValue` (string) — The locale-resolved label — what you render. Not the same field as `value`.
- `displayOrder` (number) — The owner's configured display order.
- `position` (number) — 1-based position in the returned ranking.
- `ancestors` (array, optional) — The precomputed hierarchy chain, root first, excluding the item itself — `{ itemId, value, displayValue, hierarchyLevel? }`. Use it to auto-fill parent form fields. Absent when the item has no ancestors; never an empty array.

## Implementation steps
1. Mark up one element — Give any element data-autosugges-key and data-autosugges-base-url. Optional: data-autosugges-label, -placeholder, -locale, -theme.
2. Load the browser build — Add <script src=".../sdk/v1/autosugges.js"></script>. Loading it is what triggers the one-time scan that mounts every [data-autosugges-key] element — no import, no bundler.
3. Or mount explicitly — For markup injected after that scan, or when you need the selection event, call mountAutocomplete(target, { source, label, onSelect, onError }) with a client you created yourself.
4. Style it from outside — The widget lives in a shadow root. Theme it with the documented CSS custom properties from an ancestor; host page rules cannot reach inside it, and its rules cannot leak out.

## Code — `index.html`
```html
<!-- Load the prebuilt browser build once, near the end of <body>. It is an
     IIFE — no type="module", no bundler — that also exposes window.AutoSuggesSDK
     for Option B below. -->
<script src="YOUR_AUTOSUGGES_WEB_ORIGIN/sdk/v1/autosugges.js"></script>

<!-- Option A — no JavaScript to write. Loading the script above scans for
     this attribute and mounts an accessible combobox (input + listbox + live
     region) inside its own shadow root, so page styles cannot leak in. -->
<div
  data-autosugges-key="YOUR_PUBLISHABLE_KEY"
  data-autosugges-base-url="YOUR_RUNTIME_BASE_URL"
  data-autosugges-label="City"
  data-autosugges-placeholder="Search for a city"
></div>

<!-- Option B — explicit control, for markup injected after that scan ran, or
     when you need the selection event. window.AutoSuggesSDK is the same
     module the script tag above already loaded; there is nothing further to
     import. -->
<div id="city-mount"></div>
<p id="city-error" role="alert"></p>

<script>
  const { createAutosuggesClient, mountAutocomplete } = window.AutoSuggesSDK;

  const source = createAutosuggesClient({
    baseUrl: 'YOUR_RUNTIME_BASE_URL',
    publishableKey: 'YOUR_PUBLISHABLE_KEY',
  });
  void source.bootstrap().catch(() => {});

  const mounted = mountAutocomplete(document.getElementById('city-mount'), {
    source,
    label: 'City',
    onSelect(item, { ancestors }) {
      // Wire item.value / item.displayValue / ancestors into your form.
    },
    onError(error) {
      // Never invent a message: error.message is already the SDK's safe,
      // ErrorCode-mapped text. Show it, or branch on error.code.
      document.getElementById('city-error').textContent = error.message;
    },
  });
  // mounted.destroy() removes every node and listener it added.
</script>
```

## Security requirements
- A publishable key is public by design. It is safe in client-side JavaScript, in a mobile bundle, and in a page a search engine can read. It is not a secret and does not need a proxy.
- A publishable key is not a substitute for origin control: keys are bound to an allow-list of origins, and a request from an origin the tenant has not allowed is refused with `origin_not_allowed` and is not billed. Add the deploying site’s origin in the AutoSugges dashboard before going live.
- Never place a secret key, a signing key, a service-role credential or a database URL in client code, in an environment variable prefixed for browser exposure, or in a prompt. Nothing in an AutoSugges browser or mobile integration needs one.
- An access token (`authorization: Bearer …`) is only for a list whose policy requires one. It is short-lived, and it is minted by your own server from your own AutoSugges credentials — never in the browser, never hardcoded, never committed.
- Do not log the raw query text or the response body. Log the typed error `code` and the `requestId`.
- The data attributes are visible in page source. That is fine: both values are public by design. Never add an attribute carrying a secret or an access token.

## Expected result
An accessible input and listbox appear where the target element was, isolated in a shadow root, returning suggestions from the published list.

## Validation — do these before reporting success
1. Check 1 — Load the page and confirm an input appears inside the target element and that the element gained a data-autosugges-mounted attribute.
2. Check 2 — Type below and then above the minimum query length and confirm requests start only at the threshold.
3. Check 3 — Confirm the widget is keyboard-operable and that a screen reader announces the result count.
4. Check 4 — Remove data-autosugges-base-url and confirm the element renders a safe inline message instead of throwing into the page.
5. Check 5 — If you mounted explicitly, call mounted.destroy() and confirm every node and listener is removed.

## Error codes you must handle
Every failure arrives as a typed code in the response body (and, through the SDK, as an `AutosuggesError` with that `code`). Switch on the code; never match on a message string. The codes most likely on this surface are: `invalid_key`, `origin_not_allowed`, `invalid_request`, `artifact_unavailable`. The complete vocabulary:
- `invalid_key` (HTTP 401, not retryable) — The publishable key is wrong, revoked or rotated. Check the key in the AutoSugges dashboard. Do not retry with the same key.
- `origin_not_allowed` (HTTP 403, not retryable) — The requesting origin is not on this key's allow-list. Add the origin in the dashboard. Not billed.
- `invalid_list` (HTTP 404, not retryable) — The key resolves to no list, or the list was deleted. Nothing to retry.
- `subscription_required` (HTTP 403, not retryable) — The list is shared and this consumer has no active subscription to it. Subscribe, or use a list you own.
- `list_not_published` (HTTP 409, not retryable) — The list exists but has never been published, so there is no artifact to serve. Publish it once from the dashboard.
- `token_expired` (HTTP 401, not retryable) — The access token is past its expiry. Mint a fresh one on your server and retry once. Never extend expiry on the client.
- `invalid_token` (HTTP 401, not retryable) — The access token failed signature or scope verification. Mint a new one; do not retry the same token.
- `quota_exceeded` (HTTP 200, not retryable) — The allowance for this billing scope is spent. `details.scope` says which allowance — `subscription` or `key`. The response carries no items at all, real or synthetic: render an upgrade path, and do not feed it into selection analytics. It clears at the next billing period.
- `query_too_short` (HTTP 200, not retryable) — The query is below the list's `minQueryChars` (`details.minQueryChars`). Do not issue the request at all until the input reaches it. Not billed.
- `query_too_long` (HTTP 400, not retryable) — The query exceeds the server maximum (`details.maxQueryChars`). Trim the input before sending; this is a malformed request, not something a user types.
- `invalid_request` (HTTP 400, not retryable) — The request is malformed — a missing parameter or an unusable value. `details` names what. Fix the call; retrying unchanged cannot help.
- `rate_limited` (HTTP 429, retryable) — Too many requests for this key, subscription or IP. Honour the `retryAfter` seconds in the body before retrying, and check that the input is actually debounced.
- `challenge_failed` (HTTP 403, not retryable) — A bot challenge was not satisfied on a session-establishing surface. Re-present the challenge. Not billed.
- `publish_validation_failed` (HTTP 422, not retryable) — A publish was rejected by validation (duplicates, an unresolved parent, a hierarchy cycle). The previously active version keeps serving. Fix the data and publish again.
- `compile_failed` (HTTP 500, retryable) — Compilation of a new version failed. The previously active version keeps serving; nothing at runtime changed. Retry the publish after fixing the reported cause.
- `artifact_unavailable` (HTTP 503, retryable) — A published artifact could not be read at this edge, usually mid-propagation. Retryable: wait the `retryAfter` seconds and retry once. Do not render a partial or stale result set alongside a fresh one.
- `resource_removed` (HTTP 404, not retryable) — The resource was deleted. Stop requesting it; there is nothing to retry.
- `invalid_domain` (HTTP 400, not retryable) — The submitted domain or slug is not valid or is reserved. Choose another.
- `domain_validation_failed` (HTTP 409, not retryable) — A custom-domain DNS or TLS validation did not complete. Re-check the DNS records shown in the dashboard, then revalidate.
- `forbidden` (HTTP 403, not retryable) — Your account is signed in but your workspace role does not permit this action. Ask an owner or admin to change your role, or use an account that has it.
- `internal_error` (HTTP 500, retryable) — An unexpected server-side failure. Report the `requestId` from the response. Retry at most once, with backoff.

## Notes
- Never hardcode a minimum query length or a debounce interval. Both come from `client.policy`, which the SDK fills from the bootstrap response and updates in place. The constants the SDK falls back to before the first successful bootstrap are documented defaults, not the list’s real policy.
- Render `displayValue`, store `value`. They differ: `displayValue` is resolved for the requested locale at compile time.
- A selection report is optional. Omitting it costs ranking quality over time and nothing else; it is never required for a query to work.
- The binding never throws into the host page. A configuration or query failure degrades to the widget’s own error state, so check the console and the network panel rather than expecting an exception.

## Reference
- JavaScript integration guide: https://docs.autosugges.com/integrations/vanilla-js
- All integration guides: https://docs.autosugges.com/integrations

## Frequently asked questions

### What is the minimum number of characters before a query runs?

Two by default. A list owner can change the minimum, but it can never be 1. The client reads the real value from bootstrap and sends no request below it, so do not hardcode it.

### How long does the client wait after typing before it queries?

150 milliseconds by default. The value is delivered through bootstrap and a list owner can raise it, so the client uses the policy value rather than a constant.

### Where does the publishable key go?

In the key query parameter of the request, for example /v1/query?key=YOUR_PUBLISHABLE_KEY, never in a header. The key is public by design and safe in client code. Secret keys never belong in a browser or mobile bundle, and a proxy to hide the publishable key is unnecessary.

### What happens when my query quota runs out?

The runtime returns a structured quota_exceeded response that carries no items and no placeholder suggestions, so exhaustion is never mistaken for no results. Render it from the typed error code and prompt an upgrade.

### Can my page styles break the widget?

No. The widget lives in a shadow root, so host page rules cannot reach inside it and its rules cannot leak out. Theme it with the documented CSS custom properties set on an ancestor element.

---
Canonical page: https://docs.autosugges.com/integrations/vanilla-js
