# Edge package (/kya/edge)



<Callout type="warn" title="Not on npm yet">
  `@finic/kya` is being published and can't be installed from npm yet. Email [support@finic.ai](mailto:support@finic.ai) for early access.
</Callout>

After this page your application receives a [verdict](/kya/verdicts) on every request as `kya-*` request headers, with no API call from your code. The package runs in front of your site and:

* serves the snippet and relays its reports from your own domain (`/_kya/agent.js`, `/_kya/s`);
* removes any `kya-*` header the client sent, then sets its own;
* never blocks a request. If Finic is slow or down, the request goes on without a verdict.

It needs two keys: `KYA_API_KEY`, your secret `gsk_…` [API key](/authentication), and `KYA_SITE_KEY`, a site's public `gpk_…` key ([create a site](/kya/quickstart#create-a-site)).

## Set it up [#set-it-up]

<Tabs items="['Cloudflare Workers', 'Next.js', 'Node']">
  <Tab value="Cloudflare Workers">
    For a site already proxied through Cloudflare. The Worker adds the script tag to your HTML pages itself, so your application doesn't change. In a new directory:

    ```js title="worker.js"
    export { default } from "@finic/kya/cloudflare";
    ```

    ```toml title="wrangler.toml"
    name = "kya"
    main = "worker.js"
    compatibility_date = "2025-01-01"
    routes = [{ pattern = "{your_domain}/*", zone_name = "{your_domain}" }]

    [vars]
    KYA_SITE_KEY = "gpk_…"
    ```

    ```bash
    npm init -y
    npm install @finic/kya
    npm install -D wrangler
    npx wrangler secret put KYA_API_KEY   # paste your gsk_… key
    npx wrangler deploy
    ```

    Optional: `KYA_ORIGIN_SECRET` (a secret, see [Trust the headers](#trust-the-headers)) and `KYA_SITE_ORIGIN` (your site's public origin, such as `https://www.example.com`).
  </Tab>

  <Tab value="Next.js">
    Needs Next.js 13.5.9, 14.2.25, 15.2.3 or later. Set `KYA_API_KEY` and `KYA_SITE_KEY` in the environment.

    ```bash
    npm install @finic/kya
    ```

    ```ts title="middleware.ts"
    import { kyaMiddleware } from "@finic/kya/next";

    export default kyaMiddleware({
      apiKey: process.env.KYA_API_KEY!,
      siteKey: process.env.KYA_SITE_KEY!,
    });
    ```

    On Next.js 16 the file is `proxy.ts`. Don't add a `matcher` that leaves out pages or API routes: a request the middleware doesn't see keeps whatever `kya-*` headers its client sent.

    Add the tag inside `<head>` in `app/layout.tsx`:

    ```tsx
    <script async src="/_kya/agent.js" data-site={process.env.KYA_SITE_KEY} data-endpoint="/_kya" />
    ```

    Read the verdict in server code:

    ```ts
    import { headers } from "next/headers";

    const actor = (await headers()).get("kya-actor");
    ```

    On Vercel the client's address is read for you. Anywhere else, pass `clientIp: (request) => request.headers.get("x-real-ip")` with a header your own proxy overwrites, or no visitor is ever `human`.
  </Tab>

  <Tab value="Node">
    Express, Connect or plain `http`. The package is ESM-only: from CommonJS, load it with `import("@finic/kya/node")`.

    ```bash
    npm install @finic/kya
    ```

    ```js
    import { kyaNode, snippetTag } from "@finic/kya/node";

    // First, before body parsers and routes.
    app.use(kyaNode({ apiKey: process.env.KYA_API_KEY, siteKey: process.env.KYA_SITE_KEY }));
    ```

    Put `snippetTag(process.env.KYA_SITE_KEY)` inside `<head>` of the HTML you render, and read the verdict from `req.headers["kya-actor"]`.

    The socket's address is taken as the client's. Behind a proxy or load balancer, say where the address is:

    | Option                                | Client address                                                                            |
    | ------------------------------------- | ----------------------------------------------------------------------------------------- |
    | `trustProxyHeader: "x-forwarded-for"` | The last entry of that header: the one your proxy added                                   |
    | `trustedProxies: 2`                   | With `trustProxyHeader`: that many entries from the right, for that many proxies of yours |
    | `trustProxyHeader: "x-real-ip"`       | A header your proxy overwrites                                                            |
    | `clientIp: (req) => …`                | Whatever your function returns                                                            |
  </Tab>
</Tabs>

## Request headers [#request-headers]

Your application receives these on each request. A header is left out when its value is unknown.

| Header             | Values                                                          |
| ------------------ | --------------------------------------------------------------- |
| `kya-actor`        | `human`, `ai_agent`, `automation`, `unknown`                    |
| `kya-verification` | `signed`, `network_verified`, `claimed`, `impersonated`, `none` |
| `kya-operator`     | Such as `OpenAI`                                                |
| `kya-product`      | Such as `ChatGPT-User`                                          |
| `kya-category`     | Such as `user_triggered_agent`                                  |
| `kya-confidence`   | `high`, `medium`, `low`. Only from a session                    |
| `kya-session`      | The session's id, `ksn_…`. Only from a session                  |
| `kya-source`       | Where the verdict came from, below                              |
| `kya-edge`         | Your `originSecret`, when you set one                           |

| `kya-source`  | Meaning                                                                              |
| ------------- | ------------------------------------------------------------------------------------ |
| `session`     | The visitor's browser ran the snippet, and this request comes from that browser      |
| `lookup`      | Judged from this request's IP address, user agent and signature alone. Never `human` |
| `skipped`     | Not looked at: a static asset, or a path you excluded                                |
| `unavailable` | Finic didn't answer in time                                                          |

`skipped`, `unavailable` and a missing `kya-source` mean no information. Never treat them as `human`. A visitor's first request has no session yet, so it's a `lookup`.

A session's verdict is used only when the request has the same user agent as the browser that reported, an address in the same network, and a report in the last 12 hours. A copied `kya_session` cookie doesn't make another client `human`.

## Trust the headers [#trust-the-headers]

A request that reaches your application without passing the package carries whatever `kya-*` headers its sender chose: one sent straight to your origin, or one that bypassed a failing Worker. Set `originSecret` to a long random value. It's sent as `kya-edge`; ignore every `kya-*` header unless it matches.

```js
const trusted = req.headers["kya-edge"] === process.env.KYA_ORIGIN_SECRET;
const actor = trusted ? req.headers["kya-actor"] : undefined;
```

## When Finic is slow or down [#when-finic-is-slow-or-down]

Your site keeps working. Nothing throws, and a request waits at most `timeoutMs` for its verdict.

| What happens                                                                  | What the package does                                                                  |
| ----------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| A verdict takes longer than `timeoutMs` (150 ms), or the API returns an error | The request goes on with `kya-source: unavailable` and no other verdict header         |
| 5 verdict calls in a row fail                                                 | The API isn't called for 10 seconds; requests go on at once as `unavailable`           |
| `/_kya/agent.js` can't be fetched                                             | The last good copy is served, else an empty script                                     |
| `/_kya/s` can't be relayed within 2 seconds                                   | The report is dropped with a `204`                                                     |
| A key is missing, or the two are swapped                                      | The API isn't called: every request goes on as `unavailable`, with one console warning |

## Options [#options]

| Option              | Default                |                                                                                                                                                    |
| ------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `apiKey`, `siteKey` | Required               | The `gsk_…` and `gpk_…` keys                                                                                                                       |
| `apiUrl`            | `https://api.finic.ai` |                                                                                                                                                    |
| `path`              | `/_kya`                | Where the snippet and its reports are served on your domain. Change it in the script tag too                                                       |
| `timeoutMs`         | `150`                  | The longest a request waits for its verdict                                                                                                        |
| `originSecret`      | None                   | Sent to your application as `kya-edge`                                                                                                             |
| `siteOrigin`        | None                   | Your site's public origin. Request signatures are checked against it instead of the `Host` the client sent. Set it on Node and self-hosted Next.js |
| `inject`            | `true`                 | Cloudflare only: add the script tag to HTML pages                                                                                                  |
| `exclude`           | None                   | Path prefixes that never get a verdict                                                                                                             |
| `include`           | None                   | Path prefixes that get a verdict. When set, nothing else does                                                                                      |

Without `include`, every request gets a verdict except a `GET` or `HEAD` of a static asset, such as `.js`, `.css` or an image. On Cloudflare, pass options with `createWorker((env) => ({ apiKey: env.KYA_API_KEY, siteKey: env.KYA_SITE_KEY, exclude: ["/health"] }))` as the Worker's default export.
