# BYO Storage
Source: https://docs.getmilana.ai/guides/byo-storage
Keep session recordings in your own cloud storage bucket for full data residency control.
Milana can store session recording data in a storage bucket that you own and control, rather than in Milana-managed storage. This gives you full control over data residency, retention policies, and access.
## How data flows
Session data is sent from the user's browser to Milana's ingest service, where it is buffered temporarily in encrypted-at-rest storage. Once a session window closes, the raw events are written to your bucket and immediately deleted from Milana's database.
Milana then processes the data in your bucket through several stages — encoding, generating transcripts, and building indexes — and writes all results back to the same bucket. Once a session is completed, no session recording data persists on Milana-managed storage.
The Milana web interface loads session replays directly from your bucket in the browser (by dynamically generating pre-signed URLs). This requires your bucket to have a CORS policy allowlisting our app domain.
## What stays in your bucket
* Raw session replays
* Encoded session replays
* Session transcripts
* User journey transcripts
## What Milana stores
Milana stores the following end-user metadata and derived data:
* **Metadata:** session metadata, user metadata, events, product-specific configuration, etc.
* **Derived data:** issues, user intent, taxonomies, summary statistics, indexes, etc.
Separately, Milana stores operational data related to your team's usage of the platform (e.g. logs, query history and analysis reports).
All data is handled in accordance with SOC 2 guidelines. We are **SOC 2 Type II certified**, with controls monitored by Vanta. See our [trust center](https://trust.getmilana.ai).
## Google Cloud Storage
### Create a bucket
Create a GCS bucket with the following settings. `us-east4` is strongly recommended for lowest latency.
| Setting | Value |
| ---------------------------- | ---------------------- |
| **Storage class** | Standard |
| **Autoclass** | Enabled |
| **Public access prevention** | Enforced |
| **Access control** | Uniform (bucket-level) |
| **Force destroy** | Disabled |
```hcl theme={null}
resource "google_storage_bucket" "milana_data" {
name = "your-company-milana-data"
location = "US-EAST4"
storage_class = "STANDARD"
uniform_bucket_level_access = true
public_access_prevention = "enforced"
force_destroy = false
autoclass {
enabled = true
}
cors {
origin = ["https://app.getmilana.ai"]
method = ["GET", "HEAD"]
response_header = ["Content-Type"]
max_age_seconds = 3600
}
}
```
See [Create buckets](https://cloud.google.com/storage/docs/creating-buckets#command-line) in the Google Cloud documentation.
### Grant Milana access
Grant the following Milana service accounts access to your bucket:
1. **Storage Object User** — allows Milana to read and write session data.
2. **Storage Object Viewer** — allows Milana's AI to read videos directly for transcription and analysis.
```hcl theme={null}
resource "google_storage_bucket_iam_member" "milana_access" {
bucket = google_storage_bucket.milana_data.name
role = "roles/storage.objectUser"
member = "serviceAccount:milana-storage-accessor@vantara-prod.iam.gserviceaccount.com"
}
resource "google_storage_bucket_iam_member" "milana_vertex_access" {
bucket = google_storage_bucket.milana_data.name
role = "roles/storage.objectViewer"
member = "serviceAccount:service-183693770837@gcp-sa-aiplatform.iam.gserviceaccount.com"
}
```
```bash theme={null}
gcloud storage buckets add-iam-policy-binding gs://your-company-milana-data \
--member="serviceAccount:milana-storage-accessor@vantara-prod.iam.gserviceaccount.com" \
--role="roles/storage.objectUser"
gcloud storage buckets add-iam-policy-binding gs://your-company-milana-data \
--member="serviceAccount:service-183693770837@gcp-sa-aiplatform.iam.gserviceaccount.com" \
--role="roles/storage.objectViewer"
```
### Configure CORS for replay access
Milana's session replay player loads replay event data in the Milana web app using short-lived browser access. For Google Cloud Storage, that requires a bucket CORS policy that allows `https://app.getmilana.ai`.
Without this CORS policy, session replay can fail to load in the browser.
If you used the Terraform configuration above, CORS is already included in the bucket resource.
Include the following `cors` block in your bucket resource:
```hcl theme={null}
cors {
origin = ["https://app.getmilana.ai"]
method = ["GET", "HEAD"]
response_header = ["Content-Type"]
max_age_seconds = 3600
}
```
```bash theme={null}
tmpfile="$(mktemp)"
cat > "$tmpfile" <<'EOF'
[
{
"origin": ["https://app.getmilana.ai"],
"method": ["GET", "HEAD"],
"responseHeader": ["Content-Type"],
"maxAgeSeconds": 3600
}
]
EOF
gcloud storage buckets update gs://your-company-milana-data --cors-file="$tmpfile"
rm "$tmpfile"
```
## Amazon S3
### Create a bucket
Create an S3 bucket with the following settings. `us-east-1` is strongly recommended for lowest latency.
| Setting | Value |
| --------------------------- | ----------------------------- |
| **Region** | `us-east-1` (recommended) |
| **Block all public access** | Enabled |
| **Bucket Versioning** | Disabled (or per your policy) |
| **Default encryption** | SSE-S3 or SSE-KMS |
```hcl theme={null}
resource "aws_s3_bucket" "milana_data" {
bucket = "your-company-milana-data"
}
resource "aws_s3_bucket_public_access_block" "milana_data" {
bucket = aws_s3_bucket.milana_data.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
```
```bash theme={null}
aws s3api create-bucket \
--bucket your-company-milana-data \
--region us-east-1
aws s3api put-public-access-block \
--bucket your-company-milana-data \
--public-access-block-configuration \
BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
```
### Grant Milana access
Add a bucket policy that grants Milana's service account read and write access. Replace `your-company-milana-data` with your bucket name.
```hcl theme={null}
resource "aws_s3_bucket_policy" "milana_access" {
bucket = aws_s3_bucket.milana_data.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Sid = "MilanaAccess"
Effect = "Allow"
Principal = {
AWS = "arn:aws:iam::969209892974:user/milana-storage-accessor"
}
Action = [
"s3:GetObject",
"s3:PutObject",
"s3:DeleteObject",
"s3:ListBucket",
]
Resource = [
aws_s3_bucket.milana_data.arn,
"${aws_s3_bucket.milana_data.arn}/*",
]
}
]
})
}
```
```bash theme={null}
cat > /tmp/milana-bucket-policy.json <<'EOF'
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "MilanaAccess",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::969209892974:user/milana-storage-accessor"
},
"Action": [
"s3:GetObject",
"s3:PutObject",
"s3:DeleteObject",
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::your-company-milana-data",
"arn:aws:s3:::your-company-milana-data/*"
]
}
]
}
EOF
aws s3api put-bucket-policy \
--bucket your-company-milana-data \
--policy file:///tmp/milana-bucket-policy.json
rm /tmp/milana-bucket-policy.json
```
### Configure CORS for replay access
Milana's session replay player loads replay event data in the browser. For S3, that requires a CORS configuration that allows `https://app.getmilana.ai`.
```hcl theme={null}
resource "aws_s3_bucket_cors_configuration" "milana_data" {
bucket = aws_s3_bucket.milana_data.id
cors_rule {
allowed_origins = ["https://app.getmilana.ai"]
allowed_methods = ["GET", "HEAD"]
allowed_headers = ["*"]
max_age_seconds = 3600
}
}
```
```bash theme={null}
cat > /tmp/milana-cors.json <<'EOF'
{
"CORSRules": [
{
"AllowedOrigins": ["https://app.getmilana.ai"],
"AllowedMethods": ["GET", "HEAD"],
"AllowedHeaders": ["*"],
"MaxAgeSeconds": 3600
}
]
}
EOF
aws s3api put-bucket-cors \
--bucket your-company-milana-data \
--cors-configuration file:///tmp/milana-cors.json
rm /tmp/milana-cors.json
```
## Need help?
Contact [help@getmilana.ai](mailto:help@getmilana.ai) or your onboarding specialist to complete your BYO storage setup.
# BYO Cloud
Source: https://docs.getmilana.ai/guides/byoc
Run Milana as a single-tenant install inside your own Google Cloud account.
Milana can be deployed as a single-tenant install inside your own Google Cloud account — bring your own cloud (BYOC). Every session recording, your database, and the entire analytics pipeline run within your cloud and under your IAM, and the AI analysis runs on an Anthropic account that you own. Milana only operates the software.
Milana offers three data-residency options, in increasing order of isolation:
* **Standard multi-tentant** — fully Milana-managed.
* **[BYO Storage (BYOS)](/guides/byo-storage)** — Milana-managed, but your session recordings stay in your own storage bucket.
* **BYO Cloud (BYOC)** — the full data plane runs in your cloud (this page).
BYOC is currently available on Google Cloud Platform (GCP) only.
## Architecture
A BYOC install runs in your own Google Cloud project and has three parts:
1. **Your data plane** — every Milana service (ingest, app and API, encoding, transcription, background jobs), your database, your storage buckets, your analytics warehouse, and the event pipeline. All session data is created, processed, and stored here.
2. **Your Anthropic account** — the AI agents that run the analysis. You bring the account and key; Milana authenticates with it on your behalf.
3. **Milana's control plane** — the software itself and the automation that deploys and updates it. It provisions your data plane but stores none of its data.
```mermaid theme={null}
flowchart LR
subgraph yours["Customer GCP Project"]
sdk["Browser SDK"] --> ingest["Ingest (milana-ingest.customer.com)"]
ingest --> stores[("Database · Storage")]
app["Milana app + API (customer.getmilana.ai)"] --> stores
app --> search[("Turbopuffer Index")]
app --> embed["Embedding Models + LLMs (in-VPC Vertex)"]
end
anthropic["Your Anthropic account"]
app -. "Session/User Transcripts etc" .-> anthropic
```
## What leaves your cloud
To analyze sessions, Milana sends **derived** data — query details, session transcripts — to *your* Anthropic account, where the analysis agents run. The analysis agents run under your contract, billing, and retention settings.
## Identity and access
* **Your users** sign in through your own identity provider via SSO (OIDC / SAML). Milana issues no standing end-user credentials of its own.
* **Milana operator access** is limited to deploying and operating the software. Any changes are made through least-privilege access that is visible in audit logs.
* **Turbopuffer operator access** is limited to deploying and updating Turbopuffer. Turbopuffer holds no standing access to your database, storage, or warehouse, and any change is made through least-privilege access that is visible in audit logs.
* **Secrets** — all provider keys and application secrets live only in your cloud's secret manager. Milana never holds them.
## Sub-processors
On a BYOC deployment, every provider that touches your session content runs either inside your cloud or on an account you own:
| Sub-processor | Purpose | Notes |
| --------------------- | --------------------- | ---------------------------------------------------------- |
| Google Cloud Platform | Hosts your deployment | Your own project (incl. Vertex / Gemini, in-project) |
| Turbopuffer | Vector search index | Deployed in your GCP project; data never leaves your cloud |
| Anthropic | AI analysis agents | Your workspace and key; derived text only |
| Clerk | SSO / identity | Identity claims only; never session content |
Milana's own operational sub-processors — for observability, feature management, transactional email, and internal identity — are listed in full at our [trust center](https://trust.getmilana.ai/subprocessors). On a BYOC deployment:
* **Braintrust** is disabled
* **Resend** is disabled
* **Posthog** is disabled
* **Voyage** is within-VPC (Vertex model garden)
All data is handled in accordance with SOC 2 guidelines. Milana is **SOC 2 Type II certified**, with controls monitored by Vanta.
## Need help?
Contact [help@getmilana.ai](mailto:help@getmilana.ai) or your onboarding specialist to discuss a BYOC deployment.
# Canvas Recording
Source: https://docs.getmilana.ai/guides/canvas-recording
Enable recording of HTML canvas elements in Milana session replays.
By default, Milana does not record the contents of `` elements — they appear as blank rectangles in replays. Enable canvas recording if your app uses canvas for charts, drawing tools, maps, or other visual content that is important to understand user behavior.
## Enable canvas recording
Pass `shouldRecordCanvas: true` in your init options.
```tsx theme={null}
```
```javascript theme={null}
Milana("init", "prd_YOUR_PRODUCT_ID", "key_YOUR_CLIENT_KEY",
{ environment: "production", version: "2.4.1" },
{ shouldRecordCanvas: true }
);
```
## When to enable it
* **Charts and data visualizations** rendered on canvas (e.g. Chart.js, D3 with canvas renderer)
* **Drawing or annotation tools** where the canvas content is the core user experience
* **Maps** rendered on canvas (e.g. Mapbox GL, Google Maps)
* **Games or interactive simulations**
## Performance considerations
Canvas recording periodically snapshots the canvas content and includes it in the recording event stream. This increases payload size, which can affect:
* **Network usage** — larger event batches are sent to the ingest endpoint
* **Recording buffer** — sessions with frequent canvas updates fill the event buffer faster
If your canvas updates at a high frame rate (e.g. 60fps animations), canvas recording can significantly increase payload size. Test in staging before enabling in production.
For apps with small or infrequently updated canvases (e.g. a static chart rendered once), the overhead is minimal.
# Codebase Integration
Source: https://docs.getmilana.ai/guides/codebase-integration
Connect your repositories so the Milana agent can read code alongside your session data.
Connect your codebase so the Milana agent can read source-level context — components, events, and flows — when investigating sessions.
Connecting your codebase is **optional**, but it unlocks a set of deeper workflows:
* **Source-aware analysis** — the agent can read your actual components, event names, and flows when investigating sessions, instead of guessing from the recording alone.
* **Automatic context gathering** — the agent picks up new events and product surfaces from your code so you don't have to brief it each time.
* **Launch monitoring** *(coming soon)* — Milana watches new releases land in your repos and automatically runs queries against the sessions that follow.
## Connect your repositories
Open [Settings](https://app.getmilana.ai/settings) in the Milana dashboard and scroll to the **GitHub** section.
Click **Connect GitHub**. You'll be redirected to GitHub to install the **Milana** app on the organization that owns your repos. Choose **All repositories** or **Only select repositories**, then approve. You'll be returned to Milana once the install completes.
Back in Milana, click **Add repository**, choose a repo from the list, and add a short note describing what part of the product this repo covers. The agent uses this note to understand the repo's role in your product.
## Security & privacy
Codebase access is scoped to the repos you choose and ephemeral by design.
### Scoped access
The Milana GitHub App is scoped to the repositories you explicitly select in GitHub's install screen — it cannot see or touch repos you didn't grant. Within those repos, the app can read source code and pull request data, and open pull requests on your behalf when you ask it to. You can change the repo selection or uninstall the app at any time from your GitHub organization settings.
### No source code stored at rest
Milana's database stores **only** repository metadata: the repo's owner, name, and default branch. Source code is **never** persisted to Milana's database, object storage, or search indexes.
### Ephemeral, isolated sandboxes
When the agent needs to read your code, it does so inside an isolated sandbox provisioned for a single session:
* A short-lived (1-hour) GitHub installation token is minted per session and passed to git via a credential helper. Tokens never land in process arguments, shell history, or `.git/config` inside the sandbox.
* Repositories are shallow-cloned (last 30 days of history) to minimize footprint.
* Source code does not survive sandbox deletion.
### Encryption
All traffic between your repositories, Milana, and the sandbox runs over TLS. Repository metadata stored in Milana's database is encrypted at rest.
### Revocation
You can sever access at any time:
1. **Per-repo, per-product** — unlink the repo from the product in **Settings → GitHub**.
2. Uninstall the Milana GitHub App from your GitHub organization.
If you have questions about how a specific part of your codebase is handled, email [help@getmilana.ai](mailto:help@getmilana.ai).
# iframe Recording
Source: https://docs.getmilana.ai/guides/iframe-recording
How Milana records same-origin and cross-origin iframe content.
## Same-origin iframes
Milana automatically records content inside same-origin iframes. No additional configuration is needed — if the iframe shares the same origin as the parent page, its DOM is captured as part of the session.
## Cross-origin iframes
Cross-origin iframes (iframes hosted on a different domain) are **not** recorded by default. To capture their content, you need to configure both the parent page and the iframe.
### Step 1: Enable in the parent page
Set `shouldRecordCrossOriginIframes: true` in your init options.
```tsx theme={null}
```
```typescript theme={null}
import { init } from "milana-js";
await init(
"prd_YOUR_PRODUCT_ID",
"key_YOUR_CLIENT_KEY",
{ environment: "production", version: "1.0.0" },
{ shouldRecordCrossOriginIframes: true }
);
```
```javascript theme={null}
Milana("init", "prd_YOUR_PRODUCT_ID", "key_YOUR_CLIENT_KEY",
{ environment: "production", version: "1.0.0" },
{ shouldRecordCrossOriginIframes: true }
);
```
### Step 2: Initialize inside the iframe
In the iframe's own page, load the Milana SDK and call `initCrossOriginIframe()`. This starts a lightweight recorder inside the iframe that forwards DOM events to the parent page's session.
```typescript theme={null}
import { initCrossOriginIframe } from "milana-js";
initCrossOriginIframe();
```
```html theme={null}
```
You do **not** need to pass a product ID or client key inside the iframe — the iframe recording is linked to the parent page's session automatically via `postMessage`.
## Privacy controls inside iframes
Privacy controls configured in the parent page do **not** propagate into iframes. You must apply privacy controls independently within the iframe's HTML.
Use the same CSS classes inside the iframe's markup:
```html theme={null}
```
Default input masking (`password`, `tel`, `email`) still applies automatically inside iframes.
## Content Security Policy
The parent page needs everything documented in your install quickstart. The iframe page does **not** need `connect-src` for `in.getmilana.ai` — `initCrossOriginIframe()` forwards events to the parent via `postMessage`, and the parent recorder is what reaches ingest.
The iframe page does need:
* `script-src https://cdn.getmilana.ai` — only if you load the SDK via script tag inside the iframe (also needs `'unsafe-inline'` or a nonce for the queue snippet).
* `frame-ancestors` permitting your parent origin. This is independent of Milana, but a strict iframe-side CSP can break the `postMessage` integration the SDK relies on.
## Common use cases
* **Embedded payment forms** (Stripe, Braintree) — enable cross-origin recording to see the flow, but ensure sensitive fields are blocked
* **Third-party widgets** (chat, calendars, embedded editors) hosted on a different domain
* **Micro-frontends** served from separate origins
# MCP Server
Source: https://docs.getmilana.ai/guides/mcp
Connect Claude Code, Cursor, ChatGPT, and other AI tools to Milana through the Model Context Protocol.
Milana exposes a hosted **Model Context Protocol (MCP)** server so AI tools — Claude.ai, Cursor, Codex, and others — can search sessions, look up users, and kick off Milana queries directly.
## Server details
| | |
| ------------- | ------------------------------ |
| **URL** | `https://app.getmilana.ai/mcp` |
| **Transport** | Streamable HTTP |
## Install
```bash theme={null}
claude mcp add --transport http milana https://app.getmilana.ai/mcp
```
Then run `/mcp` inside Claude Code and follow the **Authenticate** prompt to sign in.
Open **Cursor Settings → MCP & Integrations → Add new MCP server** and paste:
```json theme={null}
{
"mcpServers": {
"milana": {
"url": "https://app.getmilana.ai/mcp"
}
}
}
```
Cursor will prompt you to sign in the first time it calls a Milana tool.
Go to [chatgpt.com/#settings/Connectors](https://chatgpt.com/#settings/Connectors) (requires login).
You may have to ensure that **Developer Mode** is enabled in advanced settings.
Click **Create App** and enter the URL:
```
https://app.getmilana.ai/mcp
```
Complete the OAuth flow to connect Milana.
Open **Settings → Connectors → Add custom connector** and enter:
* **Name**: `Milana`
* **URL**: `https://app.getmilana.ai/mcp`
Claude Desktop will open a browser window to sign you in.
Custom connectors are available on Claude Pro, Max, Team, and Enterprise plans.
```bash theme={null}
codex mcp add milana --url https://app.getmilana.ai/mcp
```
Open the **Command Palette → MCP: Add Server**, choose **HTTP**, and enter:
```
https://app.getmilana.ai/mcp
```
Or add this to your workspace's `.vscode/mcp.json`:
```json theme={null}
{
"servers": {
"milana": {
"type": "http",
"url": "https://app.getmilana.ai/mcp"
}
}
}
```
For any MCP client that doesn't yet speak Streamable HTTP directly, use the [`mcp-remote`](https://www.npmjs.com/package/mcp-remote) adapter to bridge stdio to the hosted server:
```json theme={null}
{
"mcpServers": {
"milana": {
"command": "npx",
"args": ["-y", "mcp-remote", "https://app.getmilana.ai/mcp"]
}
}
}
```
## Available tools
| Tool | What it's for |
| --------------------- | ------------------------------------------------------------------ |
| `whoami` | Returns the authenticated Milana user and active product. |
| `list_products` | Lists the Milana products you can access. |
| `search_sessions` | Natural-language search for sessions, users, or moments. |
| `get_sessions` | Reads session transcripts to ground answers in real user behavior. |
| `get_users` | Returns a user's recent session history and identity. |
| `start_query` | Kicks off a deeper Milana analysis across many sessions. |
| `cancel_query` | Cancels an active query that you own. |
| `get_query` | Fetches the status and result of a running or completed query. |
| `list_recent_queries` | Lists recent queries in the active product. |
## Selecting a product
If your account can access more than one Milana product, the agent uses the product you most recently opened in the dashboard by default. To switch, just ask — for example, *"use the Acme product"* — and the agent will call `list_products` to pick the right one.
# Privacy Controls
Source: https://docs.getmilana.ai/guides/privacy
Block, mask, or ignore elements to control what Milana records in session replays.
Milana gives you granular control over what is and is not captured in session recordings. There are three mechanisms:
* **Block** — the element is replaced with a blank placeholder in the recording. Its contents are never sent to Milana.
* **Mask** — the element's text or input value is replaced with masked placeholders. The element's structure stays visible, but its text and input values are not.
* **Ignore** — user interactions on the element (clicks, inputs) are not recorded, but the element's content is still visible in the replay.
Masking applies to text and form input values only — it does not mask HTML attribute values such as `alt`, `title`, `href`, and `src`.
Passwords (`input[type="password"]`), phone numbers (`input[type="tel"]`), and email addresses (`input[type="email"]`) are always masked and cannot be revealed.
## Default CSS classes
The easiest way to apply privacy controls is to add a CSS class to the element in your HTML or JSX. The SDK respects these classes out of the box, with no additional configuration required.
| Class | Effect |
| --------------- | ------------------------------------------------------------------------------------------------ |
| `milana-block` | Element is blocked — replaced with a placeholder, contents not recorded |
| `milana-mask` | Text content and input values are replaced with masked placeholders |
| `milana-unmask` | Reveals matching elements at `high` or `xhigh`, unless another privacy rule masks or blocks them |
| `milana-ignore` | User interactions on the element are not recorded |
### Block an element
```html theme={null}
Card ending in 4242
```
### Mask text content
```html theme={null}
Jonathan Appleseed
```
### Mask an input
```html theme={null}
```
### Ignore interactions
```html theme={null}
```
## Custom classes and selectors
If you cannot use the default class names, configure your own via the `privacy` option when initializing.
```tsx theme={null}
```
```javascript theme={null}
Milana("init", "prd_...", "key_...",
{ environment: "production", version: "1.0.0" },
{
privacy: {
blockClass: "my-private",
blockSelector: "[data-sensitive]",
ignoreClass: "no-record",
ignoreSelector: "[data-no-record]",
maskTextClass: "redact-text",
maskInputClass: "redact-input",
maskSelector: "[data-mask]",
unmaskClass: "record-public",
},
}
);
```
The selector-based options (`blockSelector`, `ignoreSelector`, `maskSelector`, `unmaskSelector`) are matched against elements while the page is being recorded. Complex selectors can affect page performance — prefer simple, specific selectors.
## Full example
```tsx theme={null}
```
```javascript theme={null}
Milana("init", "prd_...", "key_...",
{ environment: "production", version: "1.0.0" },
{
privacy: {
blockClass: "milana-block",
blockSelector: "#stripe-elements, [data-payment-form]",
maskTextClass: "milana-mask",
maskInputClass: "milana-mask",
maskInputTypes: {
password: true,
tel: true,
},
shouldTrackQueryParams: true,
queryTrackingParamsDenyList: [/^invite$/i, /^signup_token$/i],
},
}
);
```
For the full list of privacy options and their defaults, see the [Privacy Options Reference](/sdk/privacy).
## Masking levels
The controls above mask individual elements. If you would rather mask everything by default and reveal only the elements you trust, raise the `maskingLevel`.
| Level | Input values | DOM text |
| ------------------ | ---------------------------------- | ---------------------------------- |
| `normal` (default) | Masked only when explicitly marked | Masked only when explicitly marked |
| `high` | All masked | Masked only when explicitly marked |
| `xhigh` | All masked | All masked |
```tsx theme={null}
```
```javascript theme={null}
Milana("init", "prd_...", "key_...",
{ environment: "production", version: "1.0.0" },
{
privacy: {
maskingLevel: "xhigh",
},
}
);
```
### Reveal trusted elements
At `high` or `xhigh`, add the `milana-unmask` class or use `unmaskSelector` to reveal elements that are safe to record — navigation, buttons, headings, translated product copy, and other non-sensitive UI:
```html theme={null}
...
```
```tsx theme={null}
```
```html theme={null}
...
```
```javascript theme={null}
Milana("init", "prd_...", "key_...",
{ environment: "production", version: "1.0.0" },
{
privacy: {
maskingLevel: "xhigh",
unmaskSelector: "nav, h1, h2, h3, [data-public]",
},
}
);
```
`milana-unmask`, `unmaskClass`, and `unmaskSelector` only reveal what the masking level masked. They never override an explicit mask (`milana-mask`, `maskSelector`), a blocked element (`milana-block`, `blockSelector`), or an always-masked input type (`password`, `tel`, `email`). Those stay masked no matter what.
If you set a custom `unmaskClass`, it replaces the default `milana-unmask` class. Set `unmaskClass` to an empty string (`""`) to disable class-based unmasking.
## Layout-preserving masking
By default, masking is implemented by replacing each character with `*`. Enable `shouldUseLayoutPreservingMasking` to replace masked text with width-matched placeholders that keep replays closer to the page's original layout.
It is recommended to enable this for applications that mask long text, especially when using `high` or `xhigh` masking.
```tsx theme={null}
```
```javascript theme={null}
Milana("init", "prd_...", "key_...",
{ environment: "production", version: "1.0.0" },
{
privacy: {
shouldUseLayoutPreservingMasking: true,
},
}
);
```
Layout-preserving masking changes how masked content is rendered, not which content is masked. It may preserve approximate word widths, hyphen positions, and line breaks. Use the `milana-block` class when an element should be recorded as a blank placeholder instead.
## iframes
Privacy controls configured in the parent page do not propagate into iframes. See the [Iframe Recording](/guides/iframe-recording) guide for setup instructions and how to apply privacy controls inside iframes.
## Data residency
For full control over where session data is stored, you can bring your own storage bucket. See the [BYO Storage](/guides/byo-storage) guide.
# Feature-flagged Rollout
Source: https://docs.getmilana.ai/guides/rollout
Roll out Milana to a subset of users using feature flags and deferred initialization.
If you want to enable Milana for a percentage of your users — or gate it behind a feature flag — use **deferred initialization**. The SDK loads but does nothing until you explicitly call `initialize()`.
This lets you control rollout from your existing feature flag system (LaunchDarkly, PostHog, Statsig, etc.) without code changes at each stage.
## How it works
1. Set `shouldDeferInitialization` on the provider (React) or delay calling `init()` (vanilla JS)
2. Wait for your feature flag to resolve
3. Call `initialize()` only when the flag is enabled
If the flag is off, the SDK stays inert — no recording, no network requests.
```tsx theme={null}
import { MilanaProvider, useMilana } from "milana-js/react";
function App() {
return (
);
}
function FeatureFlagGate() {
const { initialize } = useMilana();
const milanaEnabled = useFeatureFlagValue("milana-enabled");
useEffect(() => {
if (milanaEnabled) initialize();
}, [milanaEnabled, initialize]);
return null;
}
```
`initialize()` is idempotent — calling it more than once has no effect after the first successful call.
With the script tag approach, you control rollout by conditionally calling `init()`:
```html theme={null}
```
## Checking initialization state
```tsx theme={null}
const { isInitialized } = useMilana();
// isInitialized is true after init has completed successfully
```
```javascript theme={null}
// Enable debug mode to see session state in the console, then reload
localStorage.setItem("milana_debug_mode", "true");
```
## Queuing
Calls to `trackEvent()` and `update()` made before initialization completes are automatically queued and replayed once recording starts. You don't need to wait for `isInitialized` before calling them.
Milana also has built-in [server-side sampling](https://app.getmilana.ai/settings) — you can set a sampling rate in the dashboard to control how many sessions are recorded even after removing your feature flag.
# Introduction
Source: https://docs.getmilana.ai/index
Milana uses vision AI to watch session replays and understand the full user experience. It picks up on things your existing stack cannot see - users repeatedly tweaking workflows, silently dropping off mid-onboarding, or struggling with features that look fine in your logs.
Milana tells you what users came to your product to do and whether they succeeded.
Install the SDK to start recording and understanding your users' sessions in less than 10 minutes.
## Get started
Paste a prompt into your coding agent to set up Milana automatically.
Install the `milana-js` npm package with React bindings.
Install the `milana-js` npm package.
Add a `
```
The first `
```
Your Client Key is a public identifier meant to be included in client-side code. It does not grant access to your data.
When user information is available, call `Milana("identify", ...)` to attach their identity to the session:
```javascript theme={null}
Milana("identify", {
userId: "usr_12345",
email: "jane@example.com",
name: "Jane",
metadata: {
createdAt: "2024-03-15T00:00:00Z",
},
});
```
You can also update session-level metadata at any time:
```javascript theme={null}
Milana("updateSession", {
metadata: {
experiment: "checkout-v2",
},
});
```
Open the [Integration](https://app.getmilana.ai/integration) page. Within a few seconds of loading a page with the SDK, a new session should appear under **Latest Sessions**.
If you don't see sessions after a minute:
* Open the browser console and look for `Milana:` log messages
* Confirm you see `Milana: Ready` in the console
* Check that your Product ID starts with `prd_` and your Client Key starts with `key_`
* See the [Troubleshooting](/troubleshooting) guide for more help
***
## Full page example
```html theme={null}
```
***
## Available commands
All commands use the `Milana("command", ...)` queue syntax:
```javascript theme={null}
// Initialize recording
Milana("init", productId, clientKey, sessionInfo, options?);
// Update user identity or session metadata
Milana("update", { user: { ... }, session: { ... } });
// Track a custom event
Milana("trackEvent", "event_name", { key: "value" });
// Enable recording inside a cross-origin iframe
Milana("initCrossOriginIframe");
```
***
## Debug mode
Debug mode is controlled from `localStorage`. Run this in your browser console and reload the page:
```javascript theme={null}
localStorage.setItem("milana_debug_mode", "true");
```
API calls will be logged as `Milana [debug]: ...` messages. To disable:
```javascript theme={null}
localStorage.removeItem("milana_debug_mode");
```
Reload the page after changing the setting.
***
## What's next
Mark important actions so the AI can surface them in query results.
Block, mask, or ignore sensitive elements in recordings.
# Identify
Source: https://docs.getmilana.ai/sdk/identify
Associate the current session with a known user using identify().
Call `identify()` to link the current session to a user in your system — typically right after the user signs in. This is the simplest entry point for user association; it unlocks user-level filtering in the dashboard and enables AI queries to reason about specific users.
`identify()` requires a `userId` **and** an `email`. For partial user updates later in the session (e.g. plan changes), use [`updateUser()`](/sdk/update-user) — it leaves `email` optional. For session-level metadata, use [`updateSession()`](/sdk/update-session).
Use the `useMilana()` hook:
```tsx theme={null}
import { useEffect } from "react";
import { useMilana } from "milana-js/react";
function SignedInRoutes() {
const { user } = useAuth();
const { identify } = useMilana();
useEffect(() => {
if (user) {
void identify({
userId: user.id,
email: user.email,
name: user.name,
metadata: {
plan: user.plan,
createdAt: user.createdAt,
},
});
}
}, [user, identify]);
return <>{/* ... */}>;
}
```
```typescript theme={null}
import { identify } from "milana-js";
await identify({
userId: "usr_12345",
email: "jane@example.com",
name: "Jane",
metadata: {
createdAt: "2024-03-15T00:00:00Z",
plan: "pro",
},
});
```
```javascript theme={null}
Milana("identify", {
userId: "usr_12345",
email: "jane@example.com",
name: "Jane",
metadata: {
plan: "pro",
},
});
```
***
## Parameters
A stable, unique identifier for the user in your system. This is the primary key Milana uses to link sessions to a user. Use your database user ID or a similar permanent identifier — do not use an email address as the primary ID.
The user's email address. Used to connect user identity across your systems (e.g. support tools, CRM, data warehouse) and displayed in the dashboard.
The user's display name.
Arbitrary key-value pairs to attach to the user. Keys are strings, values can be `string`, `number`, `boolean`, `null`, or nested objects/arrays of the same types. e.g. `plan`, `team`, `country`, `role`, `accountType`.
We strongly recommend including a `createdAt` key (ISO 8601 timestamp, e.g. `"2024-03-15T00:00:00Z"`) so Milana can distinguish new users from returning users and support cohort analysis.
## Return value
`true` if the identification was applied to the session. `false` if the session was not active, the network request failed, or the session was not sampled.
## Timing
`identify()` is safe to call before `init()` completes — the SDK queues the call and replays it once the session is ready.
# Initialize
Source: https://docs.getmilana.ai/sdk/init
Start a Milana recording session with your product ID, client key, and session info.
Wrap your app with `MilanaProvider` to initialize recording automatically on mount:
```tsx theme={null}
import { MilanaProvider } from "milana-js/react";
function App() {
return (
);
}
```
### With options
```tsx theme={null}
```
### Deferred initialization
To gate Milana behind a feature flag, use deferred initialization. See the [Feature-flagged Rollout](/guides/rollout) guide for a complete walkthrough.
```typescript theme={null}
import { init } from "milana-js";
await init("prd_YOUR_PRODUCT_ID", "key_YOUR_CLIENT_KEY", {
environment: "production",
version: "1.0.0",
});
```
### With options
```typescript theme={null}
import { init } from "milana-js";
await init(
"prd_YOUR_PRODUCT_ID",
"key_YOUR_CLIENT_KEY",
{
environment: "production",
version: "1.0.0",
metadata: {
plan: "enterprise",
region: "us-east",
},
},
{
shouldRecordCanvas: false,
privacy: {
blockClass: "milana-block",
maskTextClass: "milana-mask",
maskInputTypes: {
password: true,
tel: true,
},
},
}
);
```
### Deferred initialization
To roll out Milana gradually or target specific user segments/flows, see the [Feature-flagged Rollout](/guides/rollout) guide.
```html theme={null}
```
```html theme={null}
```
### With options
```javascript theme={null}
Milana("init", "prd_YOUR_PRODUCT_ID", "key_YOUR_CLIENT_KEY",
{
environment: "production",
version: "1.0.0",
metadata: {
plan: "enterprise",
region: "us-east",
},
},
{
shouldRecordCanvas: false,
privacy: {
blockClass: "milana-block",
maskTextClass: "milana-mask",
maskInputTypes: {
password: true,
tel: true,
},
},
}
);
```
### Checking the result
Enable debug mode from your browser console to see session state, then reload the page:
```javascript theme={null}
localStorage.setItem("milana_debug_mode", "true");
// Reload, then check the console for "Milana:" log messages
```
To disable, run `localStorage.removeItem("milana_debug_mode")` and reload.
***
## Parameters
Your Milana product ID. Find it on your [Settings](https://app.getmilana.ai/settings) page.
Must start with `prd_` and be exactly 30 characters long. Passing an invalid product ID throws an error and prevents initialization.
Your Milana client key. Must start with `key_`. Find it on your [Settings](https://app.getmilana.ai/settings) page alongside your product ID.
Session-level information sent with every recording.
The environment your app is running in, for example `"production"` or `"staging"`. Used to filter sessions in the dashboard.
Your application's release version, for example `"1.0.0"`. Visible on session detail pages and available in AI queries.
Any additional key-value pairs to attach to the session at the start. Values can be any JSON-serializable type.
Optional configuration. All fields are optional.
Override the default ingest endpoint. Only change this if instructed by Milana support.
Enable recording of `` elements. Increases payload size; enable only when canvas content is critical to your analysis.
Enable recording inside cross-origin iframes. Same-origin iframes are recorded automatically. You must also call `initCrossOriginIframe()` from within each cross-origin iframe. See [iframe Recording](/guides/iframe-recording).
Disable recording of `contenteditable` elements. Enable this if you use a rich-text editor and do not want its content captured.
Privacy controls. See [Privacy Controls](/sdk/privacy) for the full reference.
React only. Skip auto-initialization on mount. Call `initialize()` from `useMilana()` later to trigger initialization manually.
## Return value
`true` if the session started and was included in the current sampling rate. `false` if the session was not sampled, the credentials were invalid, or a network error occurred. Your application is not affected either way — a `false` result simply means no data will be recorded for this session.
# SDK Overview
Source: https://docs.getmilana.ai/sdk/overview
A reference for the Milana SDK — available as an npm package with React bindings and as a CDN script tag.
The Milana SDK records user sessions and provides methods to initialize recording, identify users, update session metadata, track custom events, and stop recording.
## Installation
```bash theme={null}
npm install milana-js
```
Import from `milana-js/react` for React bindings — `MilanaProvider`, `useMilana`, `useMilanaOptional`.
See [React Setup](/quickstart/react) for the full setup guide.
```bash theme={null}
npm install milana-js
```
Import from `milana-js` for the core SDK — `init`, `identify`, `updateUser`, `updateSession`, `trackEvent`, `stopRecording`.
See [JavaScript Setup](/quickstart/js-package) for the full setup guide.
```html theme={null}
```
See [Script Tag Setup](/quickstart/script-tag) for the full setup guide.
## API surface
```tsx theme={null}
import { MilanaProvider, useMilana, useMilanaOptional } from "milana-js/react";
// Wrap your app to auto-initialize recording
// Access SDK methods from any component
const {
initialize,
isInitialized,
identify,
updateUser,
updateSession,
trackEvent,
stopRecording,
} = useMilana();
```
| Property | Type | Description |
| --------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------------- |
| `initialize` | `() => Promise<{ success: boolean }>` | Trigger initialization manually (for deferred init). |
| `isInitialized` | `boolean` | `true` after init has completed successfully. |
| `identify` | `(input: IdentifyInput) => Promise<{ success: boolean }>` | Associate the session with a known user (requires `userId` + `email`). |
| `updateUser` | `(user: UserUpdate) => Promise<{ success: boolean }>` | Refresh user identity (`email` optional). |
| `updateSession` | `(session: SessionUpdate) => Promise<{ success: boolean }>` | Update session metadata. |
| `trackEvent` | `(eventName: string, attributes?: TrackEventAttributes) => void` | Track a custom event. |
| `stopRecording` | `() => Promise<{ success: boolean }>` | End the current session; next `init()` starts a fresh one. |
| `update` | `(payload: UpdatePayload) => Promise<{ success: boolean }>` | **Deprecated** — prefer `identify` / `updateUser` / `updateSession`. |
```typescript theme={null}
import {
init,
identify,
updateUser,
updateSession,
trackEvent,
stopRecording,
} from "milana-js";
await init("prd_...", "key_...", { environment: "production", version: "1.0.0" });
await identify({ userId: "usr_123", email: "jane@example.com" });
await updateUser({ userId: "usr_123", metadata: { plan: "pro" } });
await updateSession({ metadata: { flow: "onboarding" } });
trackEvent("button_clicked", { buttonId: "signup" });
await stopRecording();
```
Call methods via the `Milana()` queue function:
```javascript theme={null}
Milana("init", "prd_...", "key_...", { environment: "production", version: "1.0.0" });
Milana("identify", { userId: "usr_123", email: "jane@example.com" });
Milana("updateUser", { userId: "usr_123", metadata: { plan: "pro" } });
Milana("updateSession", { metadata: { flow: "onboarding" } });
Milana("trackEvent", "button_clicked", { buttonId: "signup" });
Milana("stopRecording");
Milana("initCrossOriginIframe");
```
## Method pages
Start recording with your product ID, client key, and session info.
Associate sessions with known users using `identify()`.
Refresh user identity mid-session with `updateUser()`.
Attach session-level context with `updateSession()`.
Mark important user actions with named events and attributes.
End the current session immediately with `stopRecording()`.
Block, mask, or ignore sensitive elements before they are recorded.
Legacy entry point — kept for backward compatibility.
# Privacy Options
Source: https://docs.getmilana.ai/sdk/privacy
Full reference for all privacy configuration options available in the Milana SDK.
All options are nested under `options.privacy` when calling `init()` or configuring `MilanaProvider`. Every option is optional and falls back to the default value shown.
For an introduction to privacy controls and usage examples, see the [Privacy Controls](/guides/privacy) guide.
Selector-based privacy options require matching against elements while the page is being recorded. Prefer simple, specific selectors over complex selectors (deep descendant chains, `:has()`, broad attribute matches).
Sets a baseline for how aggressively Milana masks text content and form input values, layered underneath the per-element controls below. Raise it when you want to mask all text and input values by default and reveal only known-safe elements with `unmaskClass` or `unmaskSelector`. Note that session analysis will not be able to flag several classes of issues if the masking level is too high.
| Level | Input values | DOM text |
| -------- | ---------------------------------- | ---------------------------------- |
| `normal` | Masked only when explicitly marked | Masked only when explicitly marked |
| `high` | **All** masked | Masked only when explicitly marked |
| `xhigh` | **All** masked | **All** masked |
At `normal` (the default), only elements you explicitly mark — via the classes and selectors below, or the always-masked input types — are masked.
Elements with this CSS class are blocked — their content is replaced with a blank placeholder and never sent to Milana. Accepts a plain string class name or a regular expression to match multiple classes.
A CSS selector that identifies additional elements to block. Use this alongside `blockClass` for elements you cannot annotate with a class, for example third-party widgets: `'[data-private], .stripe-payment-form'`.
Elements with this class are not interacted with in the recording. Mouse events and keyboard input on these elements are omitted.
A CSS selector that identifies additional elements to ignore for interaction recording.
Text content inside elements with this class is replaced with masked placeholders in the recording. By default, Milana masks by replacing each character with `*`. Set `shouldUseLayoutPreservingMasking` to use width-matched placeholders that reduce replay layout shifts.
Input values inside elements with this class (or any ancestor with this class) are masked. Applies to ` `, ``, `
Additional `input[type]` values to always mask, regardless of class or masking level. `password`, `tel`, and `email` — are always masked.
To also always-mask number fields:
```javascript theme={null}
maskInputTypes: {
number: true
}
```
A CSS selector identifying elements whose text content **and** input values are always masked, at any masking level — the selector-based equivalent of applying both `maskTextClass` and `maskInputClass`. Use it for sensitive regions you cannot annotate with a class. Explicit masks always take precedence over `unmaskClass` and `unmaskSelector`.
Elements with this CSS class are recorded in the clear when `maskingLevel` would otherwise mask them. Use it for known-safe UI such as navigation, buttons, headings, and labels.
This option only reveals values masked by `maskingLevel`. It has no effect at `normal`, and it never overrides explicit masks, blocked elements, or always-masked input types. Setting a custom class replaces the default `milana-unmask` class. Set it to an empty string (`""`) to disable class-based unmasking.
Uses width-matched placeholders for masked text and masked input values, so masked recordings are less likely to re-wrap text and shift replay layout. This changes how masked content is rendered, not which content is masked.
It is recommended to enable this for applications that mask long text, especially when using `high` or `xhigh` masking. Password fields continue to use fixed `*` masking because browsers render them as bullets.
Layout-preserving masking may preserve approximate word widths, hyphen positions, and line breaks. Use the `milana-block` class when an element should be recorded as a blank placeholder instead.
A CSS selector identifying elements to reveal when a masking level would otherwise mask them — input values under `high`/`xhigh`, and DOM text under `xhigh`. Matching elements and their subtrees are recorded in the clear.
This option has the same semantics and precedence as `unmaskClass`. It only reveals values masked by `maskingLevel`, has **no effect** at `normal` (a warning is logged if it is set), and never overrides:
* explicit masks (`maskSelector`, `maskTextClass`, `maskInputClass`)
* blocked elements (`blockClass`, `blockSelector`)
* always-masked input types (`password`, `tel`, `email`, and any added via `maskInputTypes`)
Whether URL query parameters are recorded when the user navigates. Set to `false` to strip all query strings from recorded URLs entirely.
Additional patterns to redact from recorded URLs. The value of any matching query parameter is replaced with `--redacted--` in the recording.
These patterns extend the built-in denylist — they do not replace it. The built-in denylist redacts the following parameter names by default:
| Pattern | Matches |
| ------------- | ------------------------------- |
| `/^jwt$/i` | `jwt` |
| `/^code$/i` | `code` |
| `/token/i` | any param containing `token` |
| `/password/i` | any param containing `password` |
| `/secret/i` | any param containing `secret` |
| `/key/i` | any param containing `key` |
| `/auth/i` | any param containing `auth` |
| `/nonce/i` | any param containing `nonce` |
| `/csrf/i` | any param containing `csrf` |
To add your own patterns:
```javascript theme={null}
queryTrackingParamsDenyList: [
/^session_id$/i,
/^invite_token$/i
]
```
# Security Posture
Source: https://docs.getmilana.ai/sdk/security
How the Milana browser SDK is built, published, and maintained — open source, with a hardened supply chain and a minimal dependency footprint.
The Milana SDK runs in your users' browsers, so its integrity is part of your attack surface. This page documents how the SDK is sourced, built, published, and maintained, for security teams evaluating Milana.
## Open source
The SDK is open source and MIT licensed. The full source — including the release pipeline and dependency manifest described below — lives in a [public repository](https://github.com/VantaraAI/milana-sdk).
The published [`milana-js`](https://www.npmjs.com/package/milana-js) npm package is built from this repository — and provenance attestations let you cryptographically verify that link, as described below.
## Supply-chain integrity
Every release is produced by an auditable CI pipeline with no long-lived credentials.
| Control | How it works |
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **npm provenance** | Each published version carries a signed provenance attestation linking it to the exact source commit and CI workflow run that produced it, recorded in the public Sigstore transparency log. |
| **Trusted publishing (OIDC)** | npm publishes authenticate via short-lived OIDC tokens, not a long-lived npm token. There is no static publish credential to leak. |
| **Keyless cloud auth (OIDC)** | The pipeline authenticates to Google Cloud via Workload Identity Federation. No long-lived cloud keys are stored in the repository or CI. |
| **Environment protection** | The publish step runs in a dedicated `release` GitHub Environment gated by required reviewers and branch restrictions — a designated reviewer must approve each release, and only authorized branches can trigger one. |
| **Tag validation** | Releases are cut only from version tags matching `vMAJOR.MINOR.PATCH`; malformed tags fail the build before anything is published. |
| **Verified build** | A release re-runs the full CI suite and rebuilds the package from source immediately before publishing — the published artifact is never a stale or local build. |
| **Concurrency guard** | Releases cannot overlap; an in-progress publish is never cancelled or raced by another. |
| **Least-privilege workflows** | Every workflow defaults to no permissions; each job opts into only the scopes it needs (for example, identity-token issuance is granted solely to the publish job). |
| **Pinned GitHub Actions** | Every third-party action is pinned to a full commit SHA, not a mutable tag — blocking tag-hijack attacks against the build. |
### Verifying provenance
You can verify the provenance and signatures of the installed package against the public registry at any time:
```bash theme={null}
npm audit signatures
```
The package page on [npmjs.com](https://www.npmjs.com/package/milana-js) also displays the provenance for each published version, including the source commit and the workflow that built it.
## Dependency security
The SDK keeps its runtime surface deliberately small and gates every dependency change.
| Control | How it works |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Minimum release age** | A newly published dependency version must be public for at least 7 days before it can be installed, mitigating fast-pulled malicious releases. |
| **Frozen lockfile** | CI and releases install from a committed lockfile with no resolution drift — the lockfile is the single source of truth for the dependency graph. |
| **Vulnerability audit gate** | Every pull request runs a dependency audit that fails on any high- or critical-severity advisory. |
| **Automated updates (Dependabot)** | Dependabot opens upgrade pull requests for dependencies and GitHub Actions; each one runs through the same audit, test, and build gates before it can merge. |
### Dependency footprint
The SDK ships with a deliberately minimal runtime surface:
* **A single production dependency** — `@rrweb/record`, the industry-standard session recording library (used by Sentry, Posthog etc.)
* **React is an optional peer dependency** - The rrweb and React type packages are development-only — imported as types and erased at build time.
A minimal direct surface keeps the transitive graph and the audit scope small.
## Code integrity gates
Every pull request must pass the same checks before it can merge:
* Lint and format, type checking, tests, build
* Automated AI review
* Human review
## Reporting a vulnerability
Security issues are handled privately, never through public issues. The repository's [`SECURITY.md`](https://github.com/VantaraAI/milana-sdk/blob/main/SECURITY.md) is the canonical policy.
* **Report to** [security@getmilana.ai](mailto:security@getmilana.ai).
* **Acknowledgement** within 48 hours.
* **Fix or mitigation** targeted within 7 days.
* **Supported versions:** the `1.x` release line.
## Related
Block, mask, or ignore sensitive elements before they are recorded.
Keep session recordings in a storage bucket you own and control.
For our platform security posture, including SOC 2 Type II certification, see the [Milana Trust Center](https://trust.getmilana.ai).
# Stop Recording
Source: https://docs.getmilana.ai/sdk/stop-recording
End the current recording session immediately and allow a fresh session on the next init().
Call `stopRecording()` to programmatically end the current recording session. Common reasons to reach for it:
* **Logout flows** — stop recording when the user signs out
* **End of a workflow** — close the session at the end of a multi-step flow so it shows up as a discrete recording in the dashboard
* **Testing / QA tools** — explicitly finalize a session without waiting for the page to unload
Milana tells the server to finalize the session immediately (instead of waiting for the backend's inactivity timeout), flushes any buffered events, tears down all local recording machinery, and clears the cached session ID so a subsequent [`init()`](/sdk/init) call starts a brand-new session.
`init()` is fully supported after `stopRecording()` — you'll get a fresh `sessionId` and a completely independent recording. Use this pattern when you need to explicitly segment recordings per user or per flow.
Use the `useMilana()` hook:
```tsx theme={null}
import { useMilana } from "milana-js/react";
function LogoutButton() {
const { stopRecording } = useMilana();
const handleLogout = async () => {
await stopRecording();
await signOut();
};
return Log out ;
}
```
```typescript theme={null}
import { stopRecording } from "milana-js";
await stopRecording();
```
### Stop, then start a fresh session
```typescript theme={null}
import { init, stopRecording } from "milana-js";
await stopRecording();
await init("prd_YOUR_PRODUCT_ID", "key_YOUR_CLIENT_KEY", {
environment: "production",
version: "1.0.0",
});
```
```javascript theme={null}
Milana("stopRecording");
```
***
## Return value
`true` if a session was active and has been torn down. `false` if there was no active session.
## Behavior
When you call `stopRecording()`:
* The SDK sends a close signal to the server (`isClientAbort: true` with `clientAbortReason: "CLIENT_STOPPED"`) so the session is finalized immediately rather than waiting for the backend's inactivity timeout.
* Any buffered events are flushed in the same request.
* Local rrweb recording, event observers, interval timers, and the `pagehide` listener are removed.
* `sessionStorage.sessionId` is cleared so a subsequent `init()` starts a brand-new session rather than resuming the one you just closed.
`stopRecording()` is idempotent — calling it when no session is active simply resolves with `{ success: false }`.
# Track Events
Source: https://docs.getmilana.ai/sdk/track-events
Emit named events with optional attributes to mark important user actions in a session recording.
Milana watches session recordings directly, so it doesn't need granular event tracking the way traditional analytics tools do. We recommend tracking only a small number of high-signal events:
* **Key business drivers** — activation, conversion, cancellation, downgrades
* **Feature usage** — e.g. `product.aiAgent.firstMessage`, `report.exported`
* **Sampling helpers** — events that help Milana find the right population of sessions to analyze (though user and session metadata can also be used for this)
### Already using an event tracking tool?
If you already instrument events with a tool like Segment, Amplitude, or PostHog, you can add a `trackEvent` call alongside your existing tracking — there's no need to define a separate set of events for Milana. We don't need granular tracking, but we'll happily use it if you already have it.
```typescript theme={null}
// Your existing analytics helper
function trackAnalyticsEvent(name: string, properties: Record) {
posthog.capture(name, properties);
milana.trackEvent(name, properties); // just add this line
}
```
***
## Usage
Use the `useMilana()` hook:
```tsx theme={null}
import { useMilana } from "milana-js/react";
function UpgradeButton({ plan }: { plan: string }) {
const { trackEvent } = useMilana();
const handleClick = useCallback(() => {
trackEvent("upgrade_clicked", {
plan,
source: "pricing_page",
});
navigate("/checkout");
}, [plan, trackEvent]);
return Upgrade to {plan} ;
}
```
```typescript theme={null}
import { trackEvent } from "milana-js";
trackEvent("checkout_started");
trackEvent("report_exported", { format: "pdf", pageCount: 12 });
```
```javascript theme={null}
Milana("trackEvent", "checkout_started");
Milana("trackEvent", "report_exported", {
format: "pdf",
pageCount: 12,
includeCharts: true,
});
```
***
## Parameters
A name that describes the action that occurred. Maximum 255 characters. Must be a non-empty string.
Optional key-value pairs to attach to the event. Keys must be 1–255 characters, string values must be 1–2048 characters. Values can be `string`, `number`, `boolean`, or `null`.
Attributes with invalid keys, invalid string values, `undefined` values, or non-primitive values (objects, arrays) are silently dropped with a warning in the browser console.
## Validation rules
The SDK validates each event and attribute before recording it. Invalid values are silently dropped — the event is still recorded with the valid attributes, and a warning is printed to the browser console.
| Rule | Behavior when violated |
| ---------------------------------------------------------- | ------------------------------------------ |
| Event name is empty | Event is dropped entirely |
| Event name exceeds 255 characters | Event is dropped entirely |
| Attribute key is empty or exceeds 255 characters | Attribute is dropped, event still recorded |
| String attribute value is empty or exceeds 2048 characters | Attribute is dropped, event still recorded |
| Attribute value is `undefined` | Attribute is dropped, event still recorded |
| Attribute value is a non-primitive (object, array) | Attribute is dropped, event still recorded |
## Timing
`trackEvent()` is synchronous and returns immediately. If initialization hasn't completed yet when you call `trackEvent()`, the event is queued and replayed once the session starts. Events tracked before a session is sampled in are silently discarded.
# Update (deprecated)
Source: https://docs.getmilana.ai/sdk/update
Update user identity and session metadata using update().
`update()` is deprecated. Prefer the granular entry points: [`identify`](/sdk/identify) for initial user identification, [`updateUser`](/sdk/update-user) for partial user updates, and [`updateSession`](/sdk/update-session) for session-level metadata. `update()` remains available for backward compatibility.
Call `update()` to attach or refresh user identity and metadata on the current session. Common use cases:
* **Identify a user** — when user information becomes available, pass it to associate the session with a real user identity. This unlocks user-level filtering in the dashboard and allows AI queries to reason about specific users.
* **Add session context** — attach metadata like the current workflow, experiment variant, or feature flags at any point during a session.
* **Refresh user details** — update user metadata (e.g. plan changes, new roles) as it changes during the session.
Call `update()` as soon as user information is available. The SDK queues the call automatically if initialization hasn't completed yet.
Use the `useMilana()` hook:
```tsx theme={null}
import { useMilana } from "milana-js/react";
function Dashboard() {
const { user } = useAuth();
const { update } = useMilana();
useEffect(() => {
if (user) {
void update({
user: {
userId: user.id,
email: user.email,
name: user.name,
metadata: {
createdAt: user.createdAt,
},
},
});
}
}, [user, update]);
return <>{/* ... */}>;
}
```
### With user metadata
```tsx theme={null}
const { update } = useMilana();
update({
user: {
userId: "usr_12345",
email: "jane@example.com",
name: "Jane",
metadata: {
createdAt: "2024-03-15T00:00:00Z",
plan: "pro",
orgId: "org_42",
role: "admin",
},
},
});
```
### Update session metadata separately
```tsx theme={null}
const { update } = useMilana();
update({
session: {
metadata: {
currentFlow: "onboarding",
experimentVariant: "v2",
},
},
});
```
### Both at once
```tsx theme={null}
const { update } = useMilana();
update({
user: {
userId: "usr_12345",
email: "jane@example.com",
},
session: {
metadata: {
entryPoint: "email-invite",
},
},
});
```
```typescript theme={null}
import { update } from "milana-js";
await update({
user: {
userId: "usr_12345",
email: "jane@example.com",
name: "Jane",
metadata: {
createdAt: "2024-03-15T00:00:00Z",
},
},
});
```
### With user metadata
```typescript theme={null}
import { update } from "milana-js";
await update({
user: {
userId: "usr_12345",
email: "jane@example.com",
name: "Jane",
metadata: {
createdAt: "2024-03-15T00:00:00Z",
plan: "pro",
orgId: "org_42",
role: "admin",
},
},
});
```
### Update session metadata separately
```typescript theme={null}
import { update } from "milana-js";
await update({
session: {
metadata: {
currentFlow: "onboarding",
experimentVariant: "v2",
},
},
});
```
### Both at once
```typescript theme={null}
import { update } from "milana-js";
await update({
user: {
userId: "usr_12345",
email: "jane@example.com",
},
session: {
metadata: {
entryPoint: "email-invite",
},
},
});
```
```javascript theme={null}
Milana("update", {
user: {
userId: "usr_12345",
email: "jane@example.com",
name: "Jane",
metadata: {
createdAt: "2024-03-15T00:00:00Z",
},
},
});
```
### With user metadata
```javascript theme={null}
Milana("update", {
user: {
userId: "usr_12345",
email: "jane@example.com",
name: "Jane",
metadata: {
createdAt: "2024-03-15T00:00:00Z",
plan: "pro",
orgId: "org_42",
role: "admin",
},
},
});
```
### Update session metadata separately
```javascript theme={null}
Milana("update", {
session: {
metadata: {
currentFlow: "onboarding",
experimentVariant: "v2",
},
},
});
```
### Both at once
```javascript theme={null}
Milana("update", {
user: {
userId: "usr_12345",
email: "jane@example.com",
},
session: {
metadata: {
entryPoint: "email-invite",
},
},
});
```
***
## UpdatePayload
`update()` accepts an `UpdatePayload` — an object with an optional `user` field, an optional `session` field, or both. You must provide at least one.
### UserUpdate
Information about the user that persists across all of their sessions — things like their plan, team, country, or role. User metadata has upsert semantics across the user's lifetime: any fields you provide are merged with previously set values, so you only need to send what has changed.
A stable, unique identifier for the user in your system. This is the primary key Milana uses to link sessions to a user. Use your database user ID or a similar permanent identifier — do not use an email address as the primary ID.
The user's email address. Used to connect user identity across your systems (e.g. support tools, CRM, data warehouse) and displayed in the dashboard.
The user's display name.
Arbitrary key-value pairs to attach to the user. Keys are strings, values can be `string`, `number`, `boolean`, `null`, or nested objects/arrays of the same types. e.g. `plan`, `team`, `country`, `role`, `accountType`.
We strongly recommend including a `createdAt` key (ISO 8601 timestamp, e.g. `"2024-03-15T00:00:00Z"`) so Milana can distinguish new users from returning users and support cohort analysis.
### SessionUpdate
Context that is specific to the current session — things like feature flags, traffic origin, experiment variant, or the current workflow. Session metadata has upsert semantics within the session: any fields you provide are merged with previously set values, so you can enrich the session progressively as context becomes available.
Arbitrary key-value pairs to attach to the current session. Keys are strings, values can be `string`, `number`, `boolean`, `null`, or nested objects/arrays of the same types. e.g. `origin` (e.g. `"email-notification"`, `"marketing-site"`), `featureFlags`, `experimentVariant`, `currentFlow`.
## Return value
`true` if the update was applied to the session. `false` if the session was not active, the network request failed, or the session was not sampled.
# Update Session
Source: https://docs.getmilana.ai/sdk/update-session
Push session-level context using updateSession().
Call `updateSession()` to attach or refresh session-level metadata on the active session — feature flags, traffic origin, experiment variant, current workflow, etc. Session metadata has upsert semantics within the session: any fields you provide are merged with previously set values, so you can enrich the session progressively as context becomes available.
`updateSession()` only takes session metadata. Use [`identify`](/sdk/identify) to associate the session with a user, and [`updateUser`](/sdk/update-user) to refresh user identity.
Use the `useMilana()` hook:
```tsx theme={null}
import { useEffect } from "react";
import { useMilana } from "milana-js/react";
function ExperimentBoundary({ variant }: { variant: string }) {
const { updateSession } = useMilana();
useEffect(() => {
void updateSession({
metadata: {
experimentVariant: variant,
currentFlow: "checkout-v2",
},
});
}, [variant, updateSession]);
return null;
}
```
```typescript theme={null}
import { updateSession } from "milana-js";
await updateSession({
metadata: {
experimentVariant: "v2",
currentFlow: "onboarding",
entryPoint: "email-invite",
},
});
```
```javascript theme={null}
Milana("updateSession", {
metadata: {
experimentVariant: "v2",
currentFlow: "onboarding",
},
});
```
***
## Parameters
Arbitrary key-value pairs to attach to the current session. Keys are strings, values can be `string`, `number`, `boolean`, `null`, or nested objects/arrays of the same types. e.g. `origin` (e.g. `"email-notification"`, `"marketing-site"`), `featureFlags`, `experimentVariant`, `currentFlow`.
## Return value
`true` if the update was applied to the session. `false` if the session was not active, the network request failed, or the session was not sampled.
## Timing
`updateSession()` is safe to call before `init()` completes — the SDK queues the call and replays it once the session is ready.
# Update User
Source: https://docs.getmilana.ai/sdk/update-user
Update profile fields for the session's user with updateUser().
Call `updateUser()` to update profile fields (name, email, metadata) for the user attached to the current session. Use this for partial user updates as context evolves during the session — e.g. the user upgrades their plan, switches teams, or completes onboarding.
User metadata has upsert semantics across the user's lifetime: any fields you provide are merged with previously set values, so you only need to send what has changed.
`updateUser()` does not re-attribute an already-identified session. Once a session is linked to a user (via the first `identify` or `updateUser` call), subsequent `updateUser` calls with a different `userId` will not move the session to a different user — they only update the named user's metadata.
For the initial "user just signed in" flow with a known email, [`identify()`](/sdk/identify) is the more focused entry point. For session-level metadata, use [`updateSession()`](/sdk/update-session).
Use the `useMilana()` hook:
```tsx theme={null}
import { useMilana } from "milana-js/react";
function UpgradeButton() {
const { updateUser } = useMilana();
const handleUpgrade = async (newPlan: string) => {
await billing.upgrade(newPlan);
void updateUser({
userId: currentUser.id,
metadata: { plan: newPlan },
});
};
return handleUpgrade("pro")}>Upgrade ;
}
```
```typescript theme={null}
import { updateUser } from "milana-js";
await updateUser({
userId: "usr_12345",
metadata: {
plan: "pro",
role: "admin",
},
});
```
```javascript theme={null}
Milana("updateUser", {
userId: "usr_12345",
metadata: {
plan: "pro",
role: "admin",
},
});
```
***
## Parameters
A stable, unique identifier for the user in your system. Use your database user ID or a similar permanent identifier — do not use an email address as the primary ID. Pass the same `userId` as your prior `identify` call; a different `userId` will not re-attribute the session.
The user's email address. Used to connect user identity across your systems (e.g. support tools, CRM, data warehouse) and displayed in the dashboard.
The user's display name.
Arbitrary key-value pairs to attach to the user. Keys are strings, values can be `string`, `number`, `boolean`, `null`, or nested objects/arrays of the same types. e.g. `plan`, `team`, `country`, `role`, `accountType`.
## Return value
`true` if the update was applied. `false` if the session was not active, the network request failed, or the session was not sampled.
## Timing
`updateUser()` is safe to call before `init()` completes — the SDK queues the call and replays it once the session is ready.
# Troubleshooting & FAQ
Source: https://docs.getmilana.ai/troubleshooting
Solutions to common problems and frequently asked questions about the Milana SDK and session recording.
## SDK & Installation
Work through the following checks in order:
Open your browser's developer tools and check the **Console** tab for any errors logged by the SDK (look for messages starting with `Milana:`). A misconfigured `productId` or `clientKey` will throw an error immediately on initialization and prevent any sessions from being recorded.
In the console, confirm there are no `Milana: Failed to initialize session` messages. If you see one, the SDK could not reach the ingest endpoint — check your network tab for failed requests to `in.getmilana.ai`.
Enable debug mode to see whether the current session was sampled. Run this in your browser console, then refresh the page:
```js theme={null}
localStorage.setItem("milana_debug_mode", "true");
```
You may need to change the console log level from **Default levels** to **Verbose** to see all messages. After refresh, look for `Milana:` messages in the console — they will indicate whether the session was sampled and whether initialization succeeded.
To disable debug mode later:
```js theme={null}
localStorage.removeItem("milana_debug_mode");
```
If you need to adjust sampling rates for your product, contact [help@getmilana.ai](mailto:help@getmilana.ai).
Milana waits until **30 minutes** of inactivity have occurred before finalizing a session, and it may take an additional **10 minutes** for it to be fully processed.
Some browser ad blockers may block requests to `in.getmilana.ai`. Try disabling ad blockers, or contact [help@getmilana.ai](mailto:help@getmilana.ai) for help configuring a reverse proxy.
If your site sends a `Content-Security-Policy` header, the SDK's network requests or script may be blocked. Add the following directives:
* `connect-src https://in.getmilana.ai` — required for all installs, so the SDK can send recorded data.
* `script-src https://cdn.getmilana.ai` — required for script-tag installs, so the SDK script can load.
* For script-tag installs, the queue snippet is an inline `
```
With this pattern, any commands pushed before the script loads are processed immediately when the SDK initializes.
If you are using the `milana-js` npm package with React or a bundler, this error should not occur — the SDK is imported as a module and is always available when your code runs.
A blank replay is usually caused by one of the following:
**Canvas elements:** Canvas recording is disabled by default because it is CPU-intensive. If your app renders critical UI in a `` element, enable it explicitly:
```tsx theme={null}
```
**Iframes:** Same-origin iframes are recorded automatically. Cross-origin iframes require additional setup — see the [iframe Recording](/guides/iframe-recording) guide.
***
## FAQ
Have a question not answered here? Reach out at [help@getmilana.ai](mailto:help@getmilana.ai).
Milana records browser-side user activity using the SDK embedded in your app.
**What Milana records:**
* **DOM snapshots and mutations** — the structure and content of the page as it changes
* **User interactions** — clicks (including modifier keys), scrolls, and form input value changes (subject to [privacy controls](/guides/privacy))
* **Page navigation** — URL path changes, query parameter changes (with a [denylist](/guides/privacy) for sensitive values), and navigation type (e.g. back/forward)
* **Page visibility** — whether the tab is in the foreground or background
* **Scroll depth** — how far down the page a user scrolled
* **Download detection** — when a user triggers a file download
* **Canvas content** — only if [canvas recording](/guides/canvas-recording) is enabled
* **Session and user metadata** — only what you explicitly pass via `init()` and `update()`
* **Custom events** — any events you explicitly send with `trackEvent()`
**What Milana does not record:**
* Network requests or API calls
* HTTP headers, request bodies, or response bodies
* Console logs or JavaScript errors
* Cookies
* Local storage or session storage
* Server-side data or database contents
Milana's recording engine is built on [rrweb](https://www.rrweb.io/), the industry-standard open-source session recording library used by PostHog, Sentry, Statsig, and others. It has been tested both in simulated environments and at scale, having recorded sessions from over 50 million browsers.
Milana is designed to have minimal impact on your app. Key protections include:
* **Deferred start:** The SDK uses `requestIdleCallback` to wait until the browser is idle before beginning to record — delaying up to 10 seconds after initialization so that page load performance is not affected.
* **Buffer limits:** If the event buffer grows beyond approximately 10 MB, the SDK flushes immediately. If it reaches approximately 40 MB, recording stops and the session is aborted to protect app memory and performance.
* **Background flushing:** Events are batched and sent every 10 seconds. Payloads are compressed with gzip on supported browsers to minimize network usage.
* **Automatic retry:** If the network is temporarily unavailable, the SDK retries up to 5 times with a backoff schedule (5 s, 15 s, 30 s, 60 s, 300 s) before giving up — it never blocks the main thread while retrying.
Milana waits until **30 minutes of inactivity** before finalizing a session. After the session ends, it passes through a multi-stage processing pipeline:
1. **Ingest** — raw events are received and stored
2. **Aggregation** — events are grouped into a complete session
3. **Encoding** — the session is rendered and encoded as a video
4. **AI transcription** — the AI watches the video and produces a searchable description
5. **Indexing** — the session becomes available in the dashboard and in query results
This pipeline typically completes within **10 minutes** of a session ending. Sessions will not appear in query results until all stages are complete.