segi documentation
Connect the SDK for your environment and verify your first event.
Quick start
- Create a project in segi and copy the public key it generates.
- Install the SDK that matches your runtime (browser, Next.js, NestJS, or plain <script>).
- Initialize the SDK with your project key.
- Trigger a test error and confirm it shows up in the Issues tab.
- Turn on email alerts in Project → Settings.
Throughout this guide, replace segi_pk_live_xxxxx with your real project key. Once initialized, the SDK sends events to Segi.
Get your project key
- Go to Projects and click Create project.
- Pick a platform (
javascript,nextjs,nestjs, orother). - Optionally restrict the key to specific domains (recommended for browser keys).
- segi creates a public key like
segi_pk_live_…. You can manage and rotate keys anytime under Project → Keys.
Browser keys are public. They are meant to be shipped in your client bundle. Protect them with allowed-domain checks (see §9), rate limits, and key rotation, not secrecy.
Plain HTML / CDN
Drop two <script> tags into your page. Set window.SegiConfig before loading segi.min.js. The bundle auto-initializes, hooks window.onerror and unhandledrejection, and uses fetch, with sendBeacon as a fallback.
<script> window.SegiConfig = { projectKey: "segi_pk_live_xxxxx", environment: "production", release: "1.0.0" }; </script> <script src="https://cdn.extn.ai/segi/segi.min.js" async></script>
Or use data-* attributes instead of the global:
<script src="https://cdn.extn.ai/segi/segi.min.js" data-project-key="segi_pk_live_xxxxx" data-environment="production" data-release="1.0.0" async ></script>
Browser (npm)
Use this if you bundle your client (React, Vue, vanilla, etc.) and want types.
npm install @extn/segi-js # or pnpm add @extn/segi-js
import { Segi } from "@extn/segi-js"; Segi.init({ projectKey: "segi_pk_live_xxxxx", environment: "production", release: "1.0.0", }); // Optional: attach user / tags / breadcrumbs Segi.setUser({ id: "user_123" }); Segi.setTag("module", "checkout"); Segi.addBreadcrumb({ type: "navigation", message: "Visited /checkout", timestamp: new Date().toISOString() });
Segi.init uses the first configuration. To add recording, mergereplay into that initialization. A second init after error-only setup does not enable recording.
Next.js
npm install @extn/segi-nextjsServer-side capture via instrumentation.ts:
// instrumentation.ts (beside app/; src/instrumentation.ts for src/app) export async function register() { if (process.env.NEXT_RUNTIME === "nodejs") { const { initSegiNext } = await import('@extn/segi-nextjs'); initSegiNext({ projectKey: process.env.SEGI_PROJECT_KEY!, environment: process.env.NODE_ENV, release: process.env.NEXT_PUBLIC_APP_VERSION, }); } }
Next.js 13/14 requires experimental.instrumentationHook: true merged into the existing next.config. Next.js 15+ does not need this flag. Server initialization hooks unhandled Node.js errors; explicitly capture errors handled by Next.js in routes/actions as shown below.
For browser errors only, mount this client component once inside the root layout body. For errors plus recording, use only SegiReplayProvider in §15 instead of this component.
// app/segi-init.tsx (or src/app/segi-init.tsx) "use client"; import { initSegiBrowser } from "@extn/segi-nextjs/client"; initSegiBrowser({ projectKey: process.env.NEXT_PUBLIC_SEGI_PROJECT_KEY!, environment: process.env.NODE_ENV, release: process.env.NEXT_PUBLIC_APP_VERSION, }); export default function SegiInit() { return null; }
// Merge into app/layout.tsx (or src/app/layout.tsx): import SegiInit from "./segi-init"; // Inside <body>, before children: <SegiInit />
Next.js 15.3+ can place the browser initialization in instrumentation-client.ts beside app/ instead. Do not also mount SegiInit. For 13–15.2, use the component above.
Required env vars in your .env.local:
# server (project public key; not an account secret) SEGI_PROJECT_KEY=segi_pk_live_xxxxx # client (shipped to browser) NEXT_PUBLIC_SEGI_PROJECT_KEY=segi_pk_live_xxxxx NEXT_PUBLIC_APP_VERSION=1.0.0
Manual capture from a route handler or server action:
import { captureException } from "@extn/segi-nextjs"; export async function GET() { try { return new Response(await doWork()); } catch (e) { await captureException(e, { route: "/api/work" }); return new Response("internal error", { status: 500 }); } }
NestJS
npm install @extn/segi-nestjs// app.module.ts import { Module } from "@nestjs/common"; import { SegiModule } from "@extn/segi-nestjs"; @Module({ imports: [ SegiModule.forRoot({ projectKey: process.env.SEGI_PROJECT_KEY!, environment: process.env.NODE_ENV, release: process.env.APP_VERSION, }), ], }) export class AppModule {}
Auto-capture every uncaught exception (5xx) with the global filter:
// main.ts import { SegiService, SegiExceptionFilter } from "@extn/segi-nestjs"; const app = await NestFactory.create(AppModule); app.useGlobalFilters(new SegiExceptionFilter(app.get(SegiService)));
Manual capture from a service:
@Injectable() export class CheckoutService { constructor(private readonly segi: SegiService) {} async charge(orderId: string) { try { // ... } catch (e) { await this.segi.captureException(e, { orderId }); throw e; } } }
Manual capture
These APIs are available on Segi in the browser SDK and Next.js client:
Segi.init(options, opts?) // idempotent; { force: true } to override Segi.captureException(err, context?) // send an Error Segi.captureMessage(msg, context?) // send a string event (level defaults to 'info') Segi.setUser(user) // attaches { id, email } to future events AND the session recording (0.2.14+); null clears Segi.setTag(key, value) // string key/value pairs, indexed for filtering Segi.addBreadcrumb({ type, category?, message?, data?, timestamp }) Segi.isInitialized() // boolean Segi.close() // tear down listeners (test / hot-reload)
context can include any SegiEventDto fields: level, tags, extra, environment, release, url, etc.
Initialization options
| Option | Usage |
|---|---|
projectKey | Required: the public key issued for your project. |
environment | Optional environment label, such as development or production. Does not change the destination. |
release | Optional application version or commit ID for grouping errors by release. |
beforeSend | Browser only. Return an event synchronously to send it, or null to drop it. This does not mask DOM recordings. |
maxBreadcrumbs | Browser only. Maximum recent breadcrumbs attached to events. Default 50; 0 retains none. Use a nonnegative integer. |
Next.js server and NestJS use projectKey, environment and release. Although the shared type includes beforeSend and maxBreadcrumbs, current server SDKs do not process them. Filter or sanitize data before capture calls. SegiReplayProvider does not expose beforeSend or maxBreadcrumbs props either; use a single browser Segi.init with withReplay if you need those options alongside recording.
Segi.init({
projectKey: "segi_pk_live_xxxxx",
environment: "production",
release: "1.0.0",
maxBreadcrumbs: 30,
});
Segi.addBreadcrumb({
type: "navigation",
message: "Checkout opened",
timestamp: new Date().toISOString(),
});Manual capture on the server
Import captureException and captureMessage for Next.js server; use the injected SegiService for NestJS. Their second argument is extra data, not browser-style context overrides for level, user or tags. Server captureMessage uses info. Server SDKs do not expose setUser, setTag or addBreadcrumb.
Scrubbing & PII
Segi masks known sensitive fields before storing received error events. Fields masked in request.headers:
authorization, cookie, set-cookie, x-api-key, proxy-authorization
Keys masked in request.body, request.query, extra and tags (case-insensitive). Sensitive values inside messages, stacks or user information are not automatically removed; check them before sending:
password, passwd, *token, *secret, apiKey, authorization, cardNumber, rrn, residentNumber
In the browser SDK, you can drop or transform an event before it is sent by passing beforeSend:
Segi.init({
projectKey: "...",
beforeSend(event) {
if (event.url?.includes("/health")) return null; // drop
delete event.user?.email;
return event;
},
});Allowed domains
For browser keys, set Allowed domains on the project key so segi rejects ingestion from anywhere else. The check is on the request Origin header.
example.com *.example.com # wildcard subdomains localhost # for local dev
Server-to-server traffic (no Origin header) bypasses the domain check. Those requests are authenticated solely by the project key.
curl test
Useful for debugging your project key, allowed domains, or rate limit without an SDK. Returns 202 Accepted on success.
curl -X POST https://segiapi.extn.ai/api/ingest/events \ -H "Content-Type: application/json" \ -H "X-Segi-Project-Key: segi_pk_live_xxxxx" \ -d '{ "type": "error", "level": "error", "message": "Cannot read properties of undefined (reading id)", "errorName": "TypeError", "platform": "javascript", "runtime": "browser", "environment": "production", "release": "1.0.0", "url": "https://example.com/checkout" }'
Status codes:
202 accepted 400 invalid payload 401 missing or invalid project key 403 origin not in the project's allowed-domains list 429 rate limited
Session recording
Session recording provides DOM replay and a session timeline. It uses the same project key as error monitoring and is off by default. An OWNER or ADMIN enables it per project. The default mask hides all input values.
Next.js
// app/layout.tsx import { SegiReplayProvider } from "@extn/segi-nextjs/replay"; // ^0.2.9 export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html><body> <SegiReplayProvider publicKey={process.env.NEXT_PUBLIC_SEGI_PROJECT_KEY!} environment={process.env.NODE_ENV} release={process.env.NEXT_PUBLIC_APP_VERSION} sample={100} mask={{ inputs: "all", class: "segi-mask" }} /> {children} </body></html> ); }
Replace existing browser initSegiBrowser, Segi.init, or SegiInit, including initialization in instrumentation-client.ts, with this provider. Keep server instrumentation.ts. Supply path prefixes in blockRoutes to exclude routes; the console deny-list requires segi-js 0.2.16 / segi-nextjs 0.2.11 and the updated server. It combines with SDK paths on the next full page load. Older SDKs must use blockRoutes.
The new SDK defers recording and analytics until server policy is available, retrying failures every 30 seconds. Error monitoring continues. Update the URL before rendering excluded content and notify after rendering allowed content. Routers that render sensitive content before changing the URL need pause before transition or DOM masking. Saving settings does not confirm SDK adoption.
Browser SDK
import Segi from "@extn/segi-js"; // ^0.2.14 import { withReplay } from "@extn/segi-js/replay"; Segi.init({ projectKey: "segi_pk_live_...", replay: withReplay({ enabled: true, sample: 100, mask: { inputs: "all", class: "segi-mask" }, }), }); // In your checkout handler, after the recorder is active: // Segi.replay.event("checkout_started", { amount: 9900 });
Merge replay into the existing error initializer; initialize only once. rrweb loads dynamically and stays out of the main bundle unless you call withReplay(). Mark sensitive regions with className="segi-mask"— the rule climbs to descendants too.
Open Project → Recordings for sessions, DOM replay, and timelines. After enabling recording, interact and scroll for at least 30 seconds, then confirm successful/api/trace/replay uploads in developer tools. Input mask modes areall (default: every input), sensitive (password/email/tel/number), and none (password only). segi-mask excludes a whole region.
Recording options
| Option | Usage |
|---|---|
enabled | withReplay only. Defaults to true; false disables replay activation, not error capture. An OWNER/ADMIN must also enable project recording in the console. |
sample | Default 100. Recording selection probability from 0 to 100 percent. A value of 20 selects approximately 20%; initialization rolls again, including on reload. Does not sample error events. |
blockRoutes | Defaults to an empty list. Matches pathname prefixes: /auth excludes both /auth/login and /author. Configure before entering sensitive routes. |
mask.inputs | Default all. all masks input values; sensitive masks password/email/tel/number; none still masks passwords. |
mask.class | Default segi-mask. Blocks the matching DOM region and its descendants. |
user | Next.js provider only. Pass { id, email? }; null clears identity, while undefined leaves identity under manual Segi.setUser control. |
SegiReplayProvider applies sample, blockRoutes, mask, environment and release on initial mount. Later user changes are synchronized; other prop changes do not reinitialize the SDK.
// Include this in your single browser initialization. replay: withReplay({ sample: 20, blockRoutes: ["/auth", "/account/payment"], mask: { inputs: "all", class: "segi-mask" }, })
Recording controls and activity
pause/resume pause and resume DOM recording. They do not delete collected data or stop all error capture. Use blockRoutes for persistent route exclusions.
Segi.replay.pause(); Segi.replay.resume(); // Record a business action on the session timeline. Segi.replay.event("checkout_started", { itemCount: 2 }); // Non-Next.js SPA: call after the router updates the URL. Segi.replay.notifyRouteChange(); // After login / logout: Segi.setUser({ id: String(user.id) }); Segi.setUser(null);
event sends only while the replay session is active and unpaused. Names are limited to 64 characters; keep passwords and payment details out of meta. The Next.js provider reports pathname changes automatically. Other SPAs must call notifyRouteChange after navigation for page tracking and exclusions. Initialization on a blocked route defers replay until an allowed page is rendered and notifyRouteChange is called. Navigation does not override manual pause.
// Next.js: update identity as authentication state changes. <SegiReplayProvider user={user ? { id: String(user.id) } : null} publicKey={process.env.NEXT_PUBLIC_SEGI_PROJECT_KEY!} />
Automatic session summary & UX friction
When a session ends, segi distills the raw replay into a human-readable session summary (pages with dwell time and scroll depth, every click with the element's resolved label) shown on the recording detail page. The same pass derives rage_click, dead_click, and u_turn friction events onto the timeline and the marketing dashboard. No additional SDK setup is needed. Summaries may take time to appear after the session ends.
User attribution & internal-IP filter
One Segi.setUser({ id: String(user.id) }) call ties session recordings and error events to the same system user id (SDK 0.2.14+; on Next.js use the provider's user prop). Both lists gain a User ID filter and the detail pages cross-link. Under Organization → IP filter you can register your own/office IPs (CIDR supported) to stop collecting internal traffic org-wide, and preview-then-delete data already collected from a given IP.
Set it up with MCP (Claude Code, Cursor, etc.)
The same MCP server used for error monitoring also exposes session-recording setup tools. Register it once and ask your agent to wire it up:
claude mcp add segi-nextjs -- npx -y @extn/segi-mcp-nextjs
Then ask the agent:
Add segi session recording to this Next.js project. My project key is segi_pk_live_...
The agent calls these tools to fetch the patches and a probe snippet, then applies them to your repo:
get_session_recording_setup(publicKey?, blockRoutes?)— patches: mount <SegiReplayProvider> in app/layout.tsx, add the segi-mask utility class, and a README reminder to flip the dashboard toggleget_session_recording_test_snippet()— a probe click/event snippet to verify recording is actually shipping
For NestJS projects, @extn/segi-mcp-nestjs exposes a get_session_recording_info tool that returns a server-side note and points the agent at the Next.js MCP above for the client-side setup — recording is always captured in the browser.
LLM-friendly documentation (llms.txt)
We publish plain-text guides designed to be fetched directly by LLM tools (ChatGPT, Claude, Cursor, etc.). They're narrower and more code-dense than this page so an agent can paste straight from them.
- https://segi.extn.ai/llms.txt — the index
- https://segi.extn.ai/llms/session-recording.txt — session recording integration guide (masking, quota, toggle)
- https://segi.extn.ai/llms/error-monitoring.txt — error monitoring (browser / Next.js / NestJS)
- https://segi.extn.ai/llms/health-checks.txt — HTTP health checks
- https://segi.extn.ai/llms/pm2-monitoring.txt — PM2 process monitoring
- https://segi.extn.ai/llms/mcp-read-api.txt — read API + MCP server (org API keys, agent reads your error data)
Hand the URL straight to an agent, or — if you've registered the MCP server — it will fetch the right one for you. Same content either way.
Funnel analysis
Open Visit analytics → Funnels in your project and select pages and custom events in order. Search collected items without memorizing event names or query syntax.
- Choose a date range and select a page or event. Review its title/path, session count, and latest receipt.
- Review recent receipts and the registered description, then use the step. Configure up to six steps and select View results.
- OWNER/ADMIN members can save funnels with at least two steps and edit event display names/descriptions. Saving a definition does not emit an event.
Use Custom dates to choose a start and end date. The range includes the end date in KST, up to 366 days. Pages and events already selected are excluded when adding a step.
Use Group paths / edit condition for dynamic URLs such as /reading/:id. Variables match one segment only. Exclude fixed routes such as /reading/new and preview matching paths and unique sessions. Step aliases apply only to this funnel's cards and chart.
Case and trailing slash are significant; resource IDs are not correlated between steps. With MCP, inspect preview_funnel_paths before saving or analyzing a structured steps array.
Saved funnel links can be shared with authorized users. Unsaved settings are stored as drafts in this browser and cannot be reopened in another browser.
Funnels count actions completed in order within the same session and selected date range. Individually received events may not form a conversion when sessions or order differ. Paths match exactly without query/hash. Recording settings, SDK sampling, and excluded routes also affect analytics collection.
The replay SDK collects page visits. Your developer must emit business events after confirmed success; a payment button click is not a completed payment.
// Browser: after replay initialization and confirmed success Segi.replay.event("purchase_done", { itemCount: 2 });
This API belongs to a browser session. Do not call it directly on the server. The initiating browser can emit after a server success response, but receipt can be missed if the browser closes. Never send passwords, tokens, emails, card information, or raw form values.
Instrument with an AI agent
Ask your MCP agent to inspect get_analytics_instrumentation_guide, list_analytics_items, and list_analytics_definitions. After it instruments your code, run a test action and inspect timestamps using get_analytics_receipts. Use analyze_funnel to check progression.
To save definitions/funnels through MCP, explicitly enable analytics configuration writes when creating an API key. Existing keys remain read-only. New tools require both an updated MCP package and server. Code changes and verified receipt are separate checks.
Health checks
Open a project → Health checks tab → Create health check. Each check defines:
URL+method(GET/HEAD/POST)expectedStatus— required HTTP status (default200)expectedText— substring the response body must include (optional)intervalSeconds— minimum 15timeoutMs— request timeoutheaders— JSON object for auth tokens etc.
Each run is classified as:
UP— status matches, and (if set)expectedTextis in the bodyTEXT_MISMATCH— status matches but body does not includeexpectedTextDOWN— HTTP status did not matchERROR— request failed or timed out
The latest 50 results are kept per check and can be viewed on the check detail page.
PM2 monitoring
On any host that runs PM2, drop the agent script and post your pm2 jlist output to segi on a schedule. Each report replaces the snapshot for that instance, so processes that vanish from a later report disappear from the UI.
One-line install (recommended)
On any host with node ≥ 18 and pm2, the one-liner below drops the agent into ~/.segi, registers it with pm2, and starts reporting immediately. Re-running the same command safely re-installs with the new key.
curl -fsSL https://segi.extn.ai/install-pm2-agent.sh \ | SEGI_PROJECT_KEY=segi_pk_live_xxxxx bash
Using wget:
wget -qO- https://segi.extn.ai/install-pm2-agent.sh \ | SEGI_PROJECT_KEY=segi_pk_live_xxxxx bash
Optional env vars: SEGI_INSTANCE, SEGI_INTERVAL_MS, SEGI_AGENT_NAME, SEGI_AGENT_DIR.
To make pm2 survive reboots, run once as root:
pm2 startup pm2 save
Manual install
The agent is ~30 lines of Node. To inspect or customize first, download it:
curl -O https://segi.extn.ai/install-pm2-agent.sh less install-pm2-agent.sh # inspect SEGI_PROJECT_KEY=segi_pk_live_xxxxx bash install-pm2-agent.sh
The ingestion endpoint is a plain POST, so the same body (the JSON output of pm2 jlist) can be sent from cron or a systemd timer if pm2 isn't your scheduler.
Notifications
On a project's Settings tab, enable Email the team when a new issue is discovered. When a brand-new error fingerprint is first persisted in that project, segi emails every org member who:
- Has email notifications enabled on their org membership
- Has a verified email address
Members verify their email from the My account page. The alert email contains a deep link straight to the issue page so you can investigate without digging through the dashboard.
AI agent (MCP)
Connect a Model Context Protocol (MCP) server to Claude Code, Cursor, or any MCP-aware coding agent. The agent then runs the install command, sets up env vars, and writes the instrumentation files into your repo for you.
For a Next.js project:
claude mcp add segi-nextjs -- npx -y @extn/segi-mcp-nextjs
For a NestJS project:
claude mcp add segi-nestjs -- npx -y @extn/segi-mcp-nestjs
Then ask the agent:
Add segi error monitoring to this project. My project key is segi_pk_live_...
The agent calls the following tools to fetch the install command, env vars, and file contents needed for setup:
get_install_command(packageManager)— install command for pnpm/npm/yarn/bunget_required_env_vars()— the env vars to setget_setup_files(publicKey?)— instrumentation.ts / app/segi-init.tsx for Next.js; patches for app.module.ts / main.ts for NestJSget_test_snippet(s)— snippets to verify ingestion is working
The MCP server itself doesn't write any code — it only describes what to install and what files to create. Your agent applies the changes. The same `npx` command works for any MCP-aware tool (Cursor, etc.).
Read your segi data and fix bugs (@extn/segi-mcp)
Separate from the setup helpers, @extn/segi-mcp is a MCP server that gives your agent access to live monitoring data — issues, events, stack traces, stats — so it can look up an error in segi and fix the root cause in your codebase.
- Create a key under Organization → API keys (OWNER/ADMIN only). The plaintext
segi_sk_live_…key is shown once at creation. - Connect your agent:
claude mcp add segi -e SEGI_SECRET_KEY=segi_sk_live_xxx -- npx -y @extn/segi-mcpThen ask the agent:
Find the noisiest error in segi and fix the root cause in this codebase.
Monitoring reads and analytics tools are available. Only configuration saves require explicit write permission:
list_projects, get_overview, list_issues, get_issue, get_issue_events, search_events, get_event, get_project_stats, get_analytics_instrumentation_guide, list_analytics_items, list_analytics_definitions, get_analytics_receipts, preview_funnel_paths, analyze_funnel, save_analytics_definition
Keys are org-scoped (optionally restricted to one project), stored as SHA-256 hashes only, revocable instantly, and rate-limited per key (default 60 req/min). Existing keys remain read-only; new keys may explicitly enable analytics configuration writes. Sensitive fields (IP, hashed emails) are stripped from event responses. Full REST endpoint reference: llms/mcp-read-api.txt.
Plans & billing
There are three plans (Free / Team / Enterprise); a plan applies to an organization. See the pricing page for limits and the payment & refund terms page for billing conditions.
- When you hit a cap, only the affected feature pauses new collection for the rest of the month (events, session recordings).
- Org owners get a one-time email per period at the moment a cap is reached.
- Register a payment method and manage your subscription from the billing screen in the console.
- Plan changes / cancellation are owner-only via Organization → Billing.
Enterprise
For custom capacity or operating requirements, contact us. We will review your requirements and discuss the available options.