// On this page

Integrate segi in under 5 minutes

This guide is for developers adding segi to an application. You’ll need a segi account before you begin. Start free

1. Quick start

  1. Create a project in segi and copy the public key it generates.
  2. Install the SDK that matches your runtime (browser, Next.js, NestJS, or plain <script>).
  3. Initialize the SDK with your project key.
  4. Trigger a test error and confirm it shows up in the Issues tab.
  5. Turn on email alerts in Project → Settings.

Throughout this guide, replace segi_pk_live_xxxxx with your real project key. The SDK already knows where to send events, so you do not need to configure an endpoint. The hosted product publishes the bundle at https://cdn.extn.ai/segi/segi.min.js and ingests events at https://segiapi.extn.ai/api/ingest/events.

Self-hosting? Pass endpoint on init (or set SEGI_ENDPOINT in your env) to point at your own instance. Every SDK accepts it as an optional override.

2. Get your project key

  1. Go to Projects and click Create project.
  2. Pick a platform (javascript, nextjs, nestjs, or other).
  3. Optionally restrict the key to specific domains (recommended for browser keys).
  4. 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.

3. Plain HTML / CDN bundle

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 falls back to fetch when sendBeacon is not usable.

<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>

4. Browser SDK (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: process.env.NEXT_PUBLIC_SEGI_PROJECT_KEY!,
  environment: process.env.NODE_ENV,
  release: process.env.NEXT_PUBLIC_APP_VERSION,
});

// 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 is idempotent. Calling it twice is a no-op with a console warning. Pass { force: true } to swap config (useful for hot reload or dynamic project keys).

5. Next.js

npm install @extn/segi-nextjs

Server-side capture via instrumentation.ts:

// instrumentation.ts (project root)
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,
    });
  }
}

Client-side capture via instrumentation-client.ts:

// instrumentation-client.ts (project root)
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,
});

Required env vars in your .env.local:

# server (private)
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 });
  }
}

6. NestJS

npm install @extn/segi-nestjs
// app.module.ts
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;
    }
  }
}

7. 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/bun
  • get_required_env_vars() the env vars to set
  • get_setup_files(publicKey?) instrumentation.ts / app/segi-init.tsx for Next.js; patches for app.module.ts / main.ts for NestJS
  • get_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.).

8. Manual capture API

All SDKs expose the same surface:

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, username } to future events
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.

9. Scrubbing & PII

segi scrubs sensitive fields on both the SDK and the server. Fields removed from request.headers:

authorization, cookie, set-cookie, x-api-key, proxy-authorization

Body keys masked anywhere in the payload (case-insensitive):

password, passwd, *token, *secret, apiKey,
authorization, cardNumber, rrn, residentNumber

You can also drop or transform an event before it is sent by passing beforeSend:

Segi.init({
  projectKey: "...",
  endpoint: "...",
  beforeSend(event) {
    if (event.url?.includes("/health")) return null; // drop
    delete event.user?.email;
    return event;
  },
});

10. 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.

11. Test ingestion with curl

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

12. Remote health checks

Open a project → Health checks tab → Create health check. Each check defines:

  • URL + method (GET / HEAD / POST)
  • expectedStatus — required HTTP status (default 200)
  • expectedText — substring the response body must include (optional)
  • intervalSeconds — minimum 15
  • timeoutMs — request timeout
  • headers — JSON object for auth tokens etc.

Each run is classified as:

  • UP — status matches, and (if set) expectedText is in the body
  • TEXT_MISMATCH — status matches but body does not include expectedText
  • DOWN — HTTP status did not match
  • ERROR — request failed or timed out

The latest 50 results are kept per check and can be viewed on the check detail page.

13. PM2 process 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_ENDPOINT, 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.

14. Email 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:

  1. Has email notifications enabled on their org membership
  2. 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.

15. Session recording

Session recording in segi combines DOM replay with click & scroll heatmaps. It uses the same project key as error monitoring and is off by default — only the org owner can enable it per project. Password, email, tel, and number inputs are always masked.

Next.js

// app/layout.tsx
import { SegiReplayProvider } from "@extn/segi-nextjs/replay"; // ^0.2.8

export default function RootLayout({ children }) {
  return (
    <html><body>
      <SegiReplayProvider
        publicKey={process.env.NEXT_PUBLIC_SEGI_KEY!}
        sample={100}
      />
      {children}
    </body></html>
  );
}

endpoint defaults to https://segiapi.extn.ai; only set when self-hosting. blockRoutes is optional — password/email/tel/number inputs are auto-masked regardless of route, so omitting it preserves heatmap data on auth pages where users do still click.

Browser SDK

import Segi from "@extn/segi-js";          // ^0.2.8
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" },
  }),
});

// anywhere after init:
Segi.replay.pause();
Segi.replay.event("checkout_started", { amount: 9900 });

The replay module is delivered as a ~120 KB dynamic chunk; it stays out of the main bundle unless you call withReplay(). Mark sensitive regions with className="segi-mask"— the rule climbs to descendants too.

In the admin console, Project → Recordings lists sessions, plays DOM replays, and shows the URL × device click heatmap. The heatmap layers click cells on top of a live DOM-replay backdrop (frozen at frame 0) of a matching session — so dots read against the actual buttons people clicked, not a grid. Click a top-URL chip to swap the backdrop to the most-recent session for that page. The enable toggle and route deny-list live in Project → Settings → Recording and are owner-only.

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?, maskClass?) patches: mount <SegiReplayProvider> in app/layout.tsx, add the segi-mask utility class, and a README reminder to flip the dashboard toggle
  • get_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.

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.

16. 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.
  • Billing uses TossPayments billing-key recurring charges; the card form is hosted by segi (no Toss-side widget).
  • Plan changes / cancellation are owner-only via Organization → Billing.

17. Enterprise

Need higher event volumes, single-tenant hosting, SAML SSO, audit logs, or VPC peering / IP allow-listing? Enterprise plans cover all of those. Talk to sales or email agent@extn.ai.

Create your account →