This quickstart adds Trace to an Astro site. A script in the page identifies the visitor, and an API endpoint verifies the event with your secret key before deciding.
Before you start
You need a running Trace server, a public key (pk_...) whose allowed origins include your site, and a secret key (sk_...) for the server. The quick start guide creates both.
- 1
Install the SDKs
@trace-id/sdk-jsruns in the browser;@trace-id/sdk-nodeverifies on the server.npm install @trace-id/sdk-js @trace-id/sdk-nodepnpm add @trace-id/sdk-js @trace-id/sdk-nodeyarn add @trace-id/sdk-js @trace-id/sdk-nodebun add @trace-id/sdk-js @trace-id/sdk-node.env# .env PUBLIC_TRACE_KEY=pk_... PUBLIC_TRACE_ENDPOINT=https://id.example.com TRACE_SECRET_KEY=sk_...Only
PUBLIC_values reach the browser. Keep the secret key without that prefix. API endpoints need an on-demand rendering adapter (for example@astrojs/node). - 2
Identify on submit
astro--- // src/pages/signup.astro --- <form id="signup"> <input name="email" type="email" required /> <button>Create account</button> </form> <script> import { createClient } from '@trace-id/sdk-js'; const trace = createClient({ apiKey: import.meta.env.PUBLIC_TRACE_KEY, endpoint: import.meta.env.PUBLIC_TRACE_ENDPOINT, }); document.querySelector('#signup')!.addEventListener('submit', async (e) => { e.preventDefault(); const form = e.currentTarget as HTMLFormElement; let eventId: string | null = null; try { ({ eventId } = await trace.get({ tags: { action: 'signup' } })); } catch (err) { console.warn('Trace unavailable', (err as { code?: string }).code); // keep going without it } await fetch('/api/signup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...Object.fromEntries(new FormData(form)), eventId }), }); }); </script> - 3
Verify in an endpoint
guardRequestreads the event id from thex-trace-event-idheader, a JSON body or a form body, verifies it, and hands you the verified event or a ready response. The request body stays readable afterwards.TypeScript// src/pages/api/signup.ts import type { APIRoute } from 'astro'; import { guardRequest } from '@trace-id/sdk-node/web'; export const prerender = false; export const POST: APIRoute = async ({ request }) => { const guard = await guardRequest(request, { secretKey: import.meta.env.TRACE_SECRET_KEY, endpoint: import.meta.env.PUBLIC_TRACE_ENDPOINT, failOpen: true, reject: (event) => event.suspectScore >= 60, }); if (guard.response) return guard.response; // 400, 403, 503 or 500, with a JSON error body const { email } = await request.json(); // create the account, and store guard.event?.visitorId with it for later lookups return Response.json({ ok: true }); };Start in shadow mode
For the first week, log
event.suspectScoreandevent.reasonsinstead of blocking. Look at who would have been blocked, then pick thresholds you trust. - 4
Other backends