# 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 ``, `