Docs

JavaScript Agent

Embed the Ambriel JavaScript agent in your web app: collect device intelligence and score sessions client-side with minimal code.

The JavaScript Agent collects device intelligence in the browser and links it to your server-side transactions through a session ID: the snippet below fingerprints the visitor, you persist the session ID next to your own user session, and you attach it to every /v1/transactions/ call so the scoring engine sees device and order together.

How it works

  1. Browser — ambriel.js fingerprints the device and returns a session ID.
  2. Your backend — you save that session ID alongside your own user session.
  3. Checkout — you include the session ID in the transaction payload, and Ambriel scores device + order as one.

Keep your API key server-side

The session ID is public by design (it lives in the browser). Your x-api-key, however, must never appear in frontend code — all /v1/* calls below run on your backend, with the key in an environment variable.

Installation

Add the tracking snippet

Paste this before the closing </head> tag. It loads ambriel.js asynchronously, so it never blocks your page:

<script>
    (function(w, d, s, u, n) {
        w[n] = w[n] || function() {
            (w[n].q = w[n].q || []).push(arguments);
        };
        w[n].ready = new Promise(res => w[n]._r = res);

        var js = d.createElement(s);
        js.async = true;
        js.src = u;
        d.head.appendChild(js);
    })(window, document, 'script', 'https://cdn.ambriel.io/ambriel.js', 'ambriel');

    ambriel('create');

    ambriel.ready.then(async ambriel => {
        const session = await ambriel.getSession();

        // Example: persist the session ID on your backend
        fetch('/save-ambriel-session', { 
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ ambriel_session: session.id })
        });
    });
</script>

Save the session ID on your backend

Expose a POST /save-ambriel-session endpoint that stores the ID next to your own user session. Pick your stack once — both code blocks below follow your choice:

import os
from flask import Flask, request, session

app = Flask(__name__)
app.secret_key = os.environ["SESSION_SECRET"]

@app.post("/save-ambriel-session")
def save_ambriel_session():  
    session["ambriel_session_id"] = request.json["ambriel_session"]
    return "", 204
import express from 'express';
import session from 'express-session';

const app = express();
app.use(express.json());
app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
}));

app.post('/save-ambriel-session', (req, res) => {  
  req.session.ambrielSessionId = req.body.ambriel_session;
  res.sendStatus(204);
});
// routes/web.php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::post('/save-ambriel-session', function (Request $request) {
    $request->session()->put(
        'ambriel_session_id',
        $request->input('ambriel_session')  
    );

    return response()->noContent();
});
package main

import (
    "encoding/json"
    "net/http"
)

// Persist the ID in your own session store (cookie, Redis, ...).
func saveAmbrielSession(store map[string]string) http.HandlerFunc {  
    return func(w http.ResponseWriter, r *http.Request) {
        var body struct {
            AmbrielSession string `json:"ambriel_session"`
        }
        if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
            http.Error(w, err.Error(), http.StatusBadRequest)
            return
        }
        userID := r.Header.Get("X-User-Id") // your own user key
        store[userID] = body.AmbrielSession
        w.WriteHeader(http.StatusNoContent)
    }
}

Attach the session ID when scoring

When the order completes, read the stored ID back and send it as session to POST /v1/transactions/. The tab selection follows your choice above:

import os
import requests
from flask import request, session, jsonify

@app.post("/checkout")
def checkout():
    order = request.json["order"]
    resp = requests.post(
        "https://api.ambriel.io/v1/transactions/",
        json={
            "actionType": "purchase",
            "transactionId": order["id"],
            "transactionType": "order",
            "transactionAmount": order["total"],
            "transactionCurrency": order["currency"],
            "customer": {"id": order["customer_id"]},
            "session": session.get("ambriel_session_id"),  
        },
        headers={"x-api-key": os.environ["AMBRIEL_API_KEY"]},
    )
    resp.raise_for_status()
    return jsonify(resp.json())
import axios from 'axios';

app.post('/checkout', async (req, res) => {
  const { order } = req.body;
  const { data } = await axios.post(
    'https://api.ambriel.io/v1/transactions/',
    {
      actionType: 'purchase',
      transactionId: order.id,
      transactionType: 'order',
      transactionAmount: order.total,
      transactionCurrency: order.currency,
      customer: { id: order.customerId },
      session: req.session.ambrielSessionId,  
    },
    {
      headers: {
        'x-api-key': process.env.AMBRIEL_API_KEY,
        'Content-Type': 'application/json',
      },
    },
  );
  res.json({ risk: data });
});
// routes/web.php
use Illuminate\Support\Facades\Http;

Route::post('/checkout', function (Request $request) {
    $order = $request->input('order');

    $response = Http::withHeaders([
        'x-api-key' => config('services.ambriel.key'),
        'Content-Type' => 'application/json',
    ])->post('https://api.ambriel.io/v1/transactions/', [
        'actionType' => 'purchase',
        'transactionId' => $order['id'],
        'transactionType' => 'order',
        'transactionAmount' => $order['total'],
        'transactionCurrency' => $order['currency'],
        'customer' => ['id' => $order['customer_id']],
        'session' => $request->session()->get('ambriel_session_id'),  
    ]);

    $response->throw();

    return response()->json($response->json());
});
package main

import (
    "bytes"
    "encoding/json"
    "net/http"
    "os"
)

// ambrielSessionID is the value you persisted in step 2.
func checkout(ambrielSessionID string, order map[string]any) (map[string]any, error) {
    body, err := json.Marshal(map[string]any{
        "actionType":          "purchase",
        "transactionId":       order["id"],
        "transactionType":     "order",
        "transactionAmount":   order["total"],
        "transactionCurrency": order["currency"],
        "customer":            map[string]any{"id": order["customer_id"]},
        "session":             ambrielSessionID, 
    })
    if err != nil {
        return nil, err
    }

    req, err := http.NewRequest("POST", "https://api.ambriel.io/v1/transactions/", bytes.NewReader(body))
    if err != nil {
        return nil, err
    }
    req.Header.Set("x-api-key", os.Getenv("AMBRIEL_API_KEY"))
    req.Header.Set("Content-Type", "application/json")

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    var result map[string]any
    if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
        return nil, err
    }
    return result, nil
}

Put the key in config/services.php under services.ambriel.key (backed by an AMBRIEL_API_KEY env var), so it never lands in version control.

FAQ

Next steps