GUIDE · WEBSITE WIDGET
Add a model widget to your website
A website widget is a box on your site where visitors type something and see your model’s answer: the category a question belongs to, the tariff code for a product, or the team that should handle a request. Your website’s server asks StayCharted, so your API key is never in the page.
How it works
- A visitor types in the widget on your page.
- Your server checks the text and verifies a bot-check token.
- Your server calls
POST /api/v1/models/{id}/classifywith your API key. - It returns only the category, confidence and an unsure flag to the page.
What you need
- A published model and a dedicated API key. Essentials and Business include the API. API reference →
- A backend: Node, Python, WordPress, Wix Velo with its Secrets Manager, or a serverless function such as Cloudflare Workers, Netlify Functions or AWS Lambda. Static HTML alone cannot safely hold your API key.
- A bot check. This example uses Cloudflare Turnstile. Configure your actual website hostname.
Keep it safe
- Keep the API key on your server, in environment variables or a secrets manager.
- Fix the model on the server. A visitor must not choose a model ID.
- Limit input before parsing. These examples cap the request at 4,000 bytes and accept up to 1,000 characters.
- Verify every bot token on the server, including its hostname and
widgetaction. Origin checks alone do not stop automated requests. - Return only the answer. Do not echo questions or upstream errors. Render labels as text, never HTML.
- Use a dedicated key so you can revoke this widget independently.
- Watch usage. Each successful question uses a prediction. Workspace API limits and plan allowances apply. Turnstile does not replace a per-visitor rate limit; add a shared rate limiter at your gateway if needed.
- Avoid personal information. Tell visitors not to enter it. Questions below the model’s review cutoff go to the Review Queue with their text. A low cutoff reduces retention; it does not guarantee none is kept.
- Choose your review threshold. The examples mark confidence below 50% as unsure. This display flag is separate from your model’s saved review cutoff, which controls the Review Queue. Confidence is not accuracy.
Plan for questions your model doesn’t cover. A model only knows the categories it was trained on. Ask this one about something other than banking and it still picks its closest category. Low-confidence answers are flagged for review, but off-topic questions can sometimes receive high confidence too. In your own model, add an Other category with representative examples of questions you don’t route, then test how well it recognizes them.
Connect the browser to your server
Render Turnstile with action: "widget". Its callback gives your browser a token. Send {widget: "support", text, token} as JSON to your same-origin /api/widget route. Disable the submit button while waiting, reset the challenge after each attempt, and clear expired tokens. Show the returned label using text content, with confidence and the unsure flag. Never place your StayCharted API key or model ID in this request.
Set these server variables: WIDGET_ENABLED=true, SITE_ORIGIN=https://your-domain.example (no trailing slash), MODEL_ID, STAYCHARTED_API_KEY, TURNSTILE_SECRET and TURNSTILE_SITE_KEY. The site key is public; the API key and Turnstile secret are not. Keep request-body logging off for this endpoint.
Example: Node with Express
Use Node 24 and install Express. Download core.mjs and save it beside the handler. It contains the bounded request reader, input validation, Turnstile verification, fixed-model API call and filtered response. Mount this route before a JSON body parser.
Show JavaScript example
import express from 'express';
import {Readable} from 'node:stream';
import {handleWidget} from './core.mjs';
const app=express();
// Mount before any body parser: core.mjs caps the incoming stream at 4,000 bytes.
app.post('/api/widget',async(req,res)=>{
const request=new Request('https://example.com/api/widget',{
method:'POST',headers:req.headers,body:Readable.toWeb(req),duplex:'half'
});
const result=await handleWidget(request,{
enabled:process.env.WIDGET_ENABLED==='true',
origin:process.env.SITE_ORIGIN,apiUrl:'https://amt.staycharted.com',
apiKey:process.env.STAYCHARTED_API_KEY,secret:process.env.TURNSTILE_SECRET,
siteKey:process.env.TURNSTILE_SITE_KEY,
widgets:{support:{modelId:process.env.MODEL_ID,title:'Your categories'}}
});
res.status(result.status).set(Object.fromEntries(result.headers)).send(await result.text());
});
app.listen(process.env.PORT||3000);
Example: Python with Flask
Install Flask and requests. Configure the server variables above and run this application using your production WSGI server. Flask rejects requests larger than the configured cap.
Show Python example
import os, math, unicodedata
from urllib.parse import urlparse, quote
import requests
from flask import Flask, request
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 4000
@app.after_request
def no_cache(response):
response.headers['Cache-Control'] = 'no-store'
return response
@app.post('/api/widget')
def widget():
if os.getenv('WIDGET_ENABLED') != 'true':
return {'error': 'Not available.'}, 404
origin = os.environ['SITE_ORIGIN'] # Exact origin, e.g. https://example.com
if request.headers.get('Origin') != origin:
return {'error': 'Not allowed.'}, 403
if request.mimetype != 'application/json':
return {'error': 'Use JSON.'}, 415
body = request.get_json(silent=True)
if not isinstance(body, dict) or body.get('widget') != 'support':
return {'error': 'Invalid request.'}, 400
text, token = body.get('text'), body.get('token')
if not isinstance(text, str) or not isinstance(token, str):
return {'error': 'Invalid request.'}, 400
text = unicodedata.normalize('NFC', text).strip()
if not 1 <= len(text) <= 1000 or not 1 <= len(token) <= 2048:
return {'error': 'Check the question and security check.'}, 400
try:
check = requests.post('https://challenges.cloudflare.com/turnstile/v0/siteverify',
json={'secret': os.environ['TURNSTILE_SECRET'], 'response': token},
timeout=8, allow_redirects=False)
verified = check.json()
if (not check.ok or not isinstance(verified, dict)
or verified.get('success') is not True
or verified.get('hostname') != urlparse(origin).hostname
or verified.get('action') != 'widget'):
return {'error': 'Please complete a fresh security check.'}, 400
model = quote(os.environ['MODEL_ID'], safe='') # Never supplied by browser
result = requests.post(f'https://amt.staycharted.com/api/v1/models/{model}/classify',
headers={'Authorization': 'Bearer ' + os.environ['STAYCHARTED_API_KEY']},
json={'input': text}, timeout=10, allow_redirects=False)
if result.status_code == 429:
return {'error': 'Please wait before trying again.'}, 429
if result.status_code != 200:
return {'error': 'The model is temporarily unavailable.'}, 502
answer = result.json()
label = answer.get('label') if isinstance(answer, dict) else None
if not isinstance(label, str) or not label.strip():
return {'error': 'Invalid model response.'}, 502
confidence = answer.get('confidence')
if type(confidence) not in (int, float) or not math.isfinite(confidence):
confidence = None
else:
confidence = max(0, min(1, confidence))
return {'label': label[:120], 'confidence': confidence,
'unsure': confidence is None or confidence < 0.5}
except (requests.RequestException, ValueError):
return {'error': 'Please try again later.'}, 502
Example: a static site with a Cloudflare Worker
Download core.mjs alongside your Worker entry point and bundle both files. Route /api/widget through the Worker on the same domain as your website. Store secrets using Workers secrets, and set the remaining variables in your deployment configuration.
Show JavaScript example
import {handleWidget} from './core.mjs';
export default {
async fetch(request,env){
// Route /api/widget on the same domain as your website; no cross-origin CORS needed.
if(new URL(request.url).pathname!=='/api/widget'||request.method!=='POST')
return new Response('Not found',{status:404});
return handleWidget(request,{
enabled:env.WIDGET_ENABLED==='true',origin:env.SITE_ORIGIN,
apiUrl:'https://amt.staycharted.com',apiKey:env.STAYCHARTED_API_KEY,
secret:env.TURNSTILE_SECRET,siteKey:env.TURNSTILE_SITE_KEY,
widgets:{support:{modelId:env.MODEL_ID,title:'Your categories'}}
});
}
};
Check it before you make it public
Test a valid question, an empty question, a question over the limit, an expired bot token and an upstream error. Verify that browser requests never contain your secret key and responses never echo the question. Check your privacy notice and usage limits.
Try our live demo → · API reference · Use Claude or ChatGPT · Plans and allowances