{"id":30110553,"url":"https://github.com/monoscope-tech/monoscope-web","last_synced_at":"2026-04-29T23:10:25.035Z","repository":{"id":306484676,"uuid":"1026338872","full_name":"monoscope-tech/monoscope-web","owner":"monoscope-tech","description":"Browser client sdk for otel instrumentation and  session replays","archived":false,"fork":false,"pushed_at":"2026-04-14T18:02:02.000Z","size":132,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-04-14T19:29:46.611Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/monoscope-tech.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-07-25T17:59:01.000Z","updated_at":"2026-04-14T18:01:44.000Z","dependencies_parsed_at":"2025-07-26T01:31:19.155Z","dependency_job_id":"186be6cb-dc7d-4b2e-9c64-c5cfab6bb1b8","html_url":"https://github.com/monoscope-tech/monoscope-web","commit_stats":null,"previous_names":["monoscope-tech/monoscope-web"],"tags_count":6,"template":false,"template_full_name":null,"purl":"pkg:github/monoscope-tech/monoscope-web","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/monoscope-tech%2Fmonoscope-web","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/monoscope-tech%2Fmonoscope-web/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/monoscope-tech%2Fmonoscope-web/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/monoscope-tech%2Fmonoscope-web/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/monoscope-tech","download_url":"https://codeload.github.com/monoscope-tech/monoscope-web/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/monoscope-tech%2Fmonoscope-web/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32443611,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-29T20:22:27.477Z","status":"ssl_error","status_checked_at":"2026-04-29T20:22:26.507Z","response_time":110,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-08-10T04:47:34.752Z","updated_at":"2026-04-29T23:10:25.030Z","avatar_url":"https://github.com/monoscope-tech.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Monoscope Browser SDK\n\nThe **Monoscope Browser SDK** is a lightweight JavaScript library for adding **session replay**, **performance tracing**, **error tracking**, and **web vitals** to your web applications.\n\nWhen used together with the [Monoscope Server SDKs](https://monoscope.tech/docs/sdks/), you gain **end-to-end observability** — seamlessly connecting user interactions in the browser to backend services, APIs, and databases.\n\nThis means you can:\n\n- **Replay user sessions** to see exactly what happened.\n- **Trace requests** from the frontend, through your backend, and into your database.\n- **Capture errors and console logs** with full context and breadcrumbs for faster debugging.\n- **Collect Web Vitals** (CLS, INP, LCP, FCP, TTFB) automatically.\n- **Track SPA navigations** across pushState, replaceState, and popstate.\n\n---\n\n## Installation\n\nInstall via **npm/bun**:\n\n```bash\nnpm install @monoscopetech/browser\n```\n\nOr include it directly in your HTML using a `\u003cscript\u003e` tag:\n\n```html\n\u003cscript src=\"https://unpkg.com/@monoscopetech/browser@latest/dist/monoscope.min.js\"\u003e\u003c/script\u003e\n```\n\n---\n\n## Quick Start\n\nInitialize Monoscope with your **API key** (found in your project settings):\n\n```javascript\nimport Monoscope from \"@monoscopetech/browser\";\n\nconst monoscope = new Monoscope({\n  apiKey: \"YOUR_API_KEY\",\n});\n\n// Identify the current user\nmonoscope.setUser({\n  id: \"user-123\",\n  email: \"user@example.com\",\n});\n```\n\nOn `localhost`, debug mode is auto-enabled — you'll see a status overlay and console diagnostics. Call `monoscope.test()` to verify your setup:\n\n```javascript\nconst result = await monoscope.test();\nconsole.log(result); // { success: true, message: \"Test span sent successfully.\" }\n```\n\n---\n\n## Configuration\n\nThe `Monoscope` constructor accepts the following options:\n\n| Name | Type | Description |\n| --- | --- | --- |\n| `apiKey` | `string` | **Required** – Your Monoscope API key (found in project settings). |\n| `serviceName` | `string` | Service name. Defaults to `location.hostname`. |\n| `projectId` | `string` | Deprecated alias for `apiKey`. |\n| `exporterEndpoint` | `string` | Endpoint for exporting traces. Defaults to Monoscope's ingest endpoint (`/v1/traces`). |\n| `metricsExporterEndpoint` | `string` | Endpoint for exporting metrics (web vitals). Defaults to the trace endpoint with `/v1/traces` → `/v1/metrics`. |\n| `propagateTraceHeaderCorsUrls` | `RegExp[]` | URL patterns where trace context headers should be propagated. Defaults to same-origin only. |\n| `resourceAttributes` | `Record\u003cstring, string\u003e` | Additional OpenTelemetry resource attributes. |\n| `instrumentations` | `unknown[]` | Additional OpenTelemetry instrumentations to register. |\n| `replayEventsBaseUrl` | `string` | Base URL for session replay events. Defaults to Monoscope's ingest endpoint. |\n| `enableNetworkEvents` | `boolean` | Include network timing events in document load spans. Default `false`. |\n| `user` | `MonoscopeUser` | Default user information for the session. |\n| `debug` | `boolean` | Enable debug logging to the console. Auto-enabled on `localhost`. |\n| `sampleRate` | `number` | Trace sampling rate from `0` to `1`. Default `1` (100%). |\n| `replaySampleRate` | `number` | Replay sampling rate from `0` to `1`. Default `1` (100%). |\n| `enabled` | `boolean` | Whether to start collecting data immediately. Default `true`. |\n| `resourceTimingThresholdMs` | `number` | Minimum resource duration (ms) to report. Default `200`. |\n| `captureResourceTiming` | `boolean` | Emit a span per resource over the threshold. Default `false` (high volume — opt-in). |\n| `captureLongTasks` | `boolean` | Emit a span per long task (\u003e50ms blocked main thread). Default `true`. |\n| `captureWebVitals` | `boolean` | Capture Core Web Vitals (LCP/INP/CLS/FCP/TTFB) as OTel metrics. Default `true`. |\n| `enableUserInteraction` | `boolean` | Trace user clicks/submits, linking them to downstream network calls. Default `true`. |\n\n---\n\n### User Object\n\nThe `MonoscopeUser` object can contain:\n\n| Name | Type | Description |\n| --- | --- | --- |\n| `email` | `string` | User's email address. |\n| `full_name` | `string` | User's full name. |\n| `name` | `string` | User's preferred name. |\n| `id` | `string` | User's unique identifier. |\n| `roles` | `string[]` | User's roles. |\n\nAdditional string-keyed attributes are also accepted and forwarded as custom user attributes.\n\n---\n\n## API\n\n### `setUser(user: MonoscopeUser)`\n\nAssociates the given user with the current session. Can be called at any time.\n\n```javascript\nmonoscope.setUser({\n  id: \"user-123\",\n  email: \"user@example.com\",\n});\n```\n\n### `startSpan\u003cT\u003e(name: string, fn: (span: Span) =\u003e T): T`\n\nCreates a custom OpenTelemetry span. The span is automatically ended when the function returns. Supports async functions.\n\n```javascript\nmonoscope.startSpan(\"checkout\", (span) =\u003e {\n  span.setAttribute(\"cart.items\", 3);\n  // ... your logic\n});\n```\n\n### `recordEvent(name: string, attributes?: Record\u003cstring, string | number | boolean\u003e)`\n\nRecords a custom event as a span with the given attributes.\n\n```javascript\nmonoscope.recordEvent(\"button_click\", {\n  \"button.name\": \"subscribe\",\n  \"button.variant\": \"primary\",\n});\n```\n\n### `getSessionId(): string`\n\nReturns the current session ID.\n\n### `getTabId(): string`\n\nReturns the current tab ID (unique per browser tab).\n\n### `test(): Promise\u003c{success: boolean, message: string}\u003e`\n\nSends a test span and flushes it to verify the connection is working.\n\n```javascript\nconst result = await monoscope.test();\nconsole.log(result.success); // true if the span was accepted\n```\n\n### `enable()` / `disable()`\n\nDynamically enable or disable all data collection.\n\n```javascript\nmonoscope.disable(); // pause collection\nmonoscope.enable();  // resume collection\n```\n\n### `isEnabled(): boolean`\n\nReturns whether the SDK is currently enabled.\n\n### `destroy(): Promise\u003cvoid\u003e`\n\nStops all collection, flushes pending data, and shuts down the OpenTelemetry provider. Call this when your application is being torn down.\n\n```javascript\nawait monoscope.destroy();\n```\n\n---\n\n## React / Next.js\n\nFor React apps, use the `@monoscopetech/browser/react` subpath export for idiomatic integration with hooks and context.\n\n```tsx\nimport { MonoscopeProvider, useMonoscope, useMonoscopeUser, MonoscopeErrorBoundary } from \"@monoscopetech/browser/react\";\n\n// Wrap your app with MonoscopeProvider\nfunction App() {\n  return (\n    \u003cMonoscopeProvider config={{ apiKey: \"YOUR_API_KEY\" }}\u003e\n      \u003cMonoscopeErrorBoundary fallback={\u003cdiv\u003eSomething went wrong\u003c/div\u003e}\u003e\n        \u003cMyApp /\u003e\n      \u003c/MonoscopeErrorBoundary\u003e\n    \u003c/MonoscopeProvider\u003e\n  );\n}\n\n// Access the instance via hook\nfunction MyApp() {\n  const monoscope = useMonoscope();\n\n  // Reactively set user when auth state changes\n  useMonoscopeUser(currentUser ? { id: currentUser.id, email: currentUser.email } : null);\n\n  return \u003cdiv\u003e...\u003c/div\u003e;\n}\n```\n\n**Next.js App Router**: The provider includes `\"use client\"` — import it in a client component or your root layout.\n\n### React API\n\n| Export | Description |\n| --- | --- |\n| `MonoscopeProvider` | Context provider. Creates and destroys the SDK instance. Strict Mode safe. |\n| `useMonoscope()` | Returns the `Monoscope` instance (or `null` during SSR). |\n| `useMonoscopeUser(user)` | Calls `setUser` reactively when the user object changes. |\n| `MonoscopeErrorBoundary` | Error boundary that reports caught errors to Monoscope. Accepts `fallback` prop. |\n\n---\n\n## Custom Instrumentation\n\n### Custom Spans\n\nUse `startSpan()` to instrument specific operations with timing and attributes. It supports both sync and async functions — the span is automatically ended when the function returns or the promise resolves.\n\n```javascript\n// Sync\nmonoscope.startSpan(\"parse-config\", (span) =\u003e {\n  span.setAttribute(\"config.size\", rawConfig.length);\n  return parseConfig(rawConfig);\n});\n\n// Async\nconst data = await monoscope.startSpan(\"fetch-dashboard\", async (span) =\u003e {\n  span.setAttribute(\"dashboard.id\", dashboardId);\n  const res = await fetch(`/api/dashboards/${dashboardId}`);\n  span.setAttribute(\"http.status\", res.status);\n  return res.json();\n});\n```\n\n### Custom Events\n\nUse `recordEvent()` to track discrete events without wrapping a code block:\n\n```javascript\nmonoscope.recordEvent(\"feature_flag_evaluated\", {\n  \"flag.name\": \"new-checkout\",\n  \"flag.value\": true,\n});\n```\n\n### React Components\n\nUse the `useMonoscope()` hook to instrument React components:\n\n```tsx\nimport { useMonoscope } from \"@monoscopetech/browser/react\";\n\nfunction CheckoutButton() {\n  const monoscope = useMonoscope();\n\n  const handleClick = () =\u003e {\n    monoscope?.startSpan(\"checkout.submit\", async (span) =\u003e {\n      span.setAttribute(\"cart.items\", cartItems.length);\n      await submitOrder();\n    });\n  };\n\n  return \u003cbutton onClick={handleClick}\u003eCheckout\u003c/button\u003e;\n}\n```\n\n### Additional OpenTelemetry Instrumentations\n\nPass extra OTel instrumentations via the `instrumentations` config to extend tracing beyond the built-in set:\n\n```javascript\nimport { LongTaskInstrumentation } from \"@opentelemetry/instrumentation-long-task\";\n\nconst monoscope = new Monoscope({\n  apiKey: \"YOUR_API_KEY\",\n  instrumentations: [new LongTaskInstrumentation()],\n});\n```\n\n---\n\n## Features\n\n### Session Replay\nCaptures DOM changes via [rrweb](https://github.com/rrweb-io/rrweb) to enable full session replay. Sensitive inputs are masked by default.\n\n### Error Tracking\nAutomatically captures `window.onerror`, unhandled promise rejections, and `console.error` calls with stack traces and breadcrumbs.\n\n### SPA Navigation Tracking\nDetects client-side navigations (`pushState`, `replaceState`, `popstate`) and emits navigation spans.\n\n### Web Vitals\nCollects Core Web Vitals (CLS, INP, LCP) and additional metrics (FCP, TTFB) via the [web-vitals](https://github.com/GoogleChrome/web-vitals) library.\n\n### Performance Observers\nReports long tasks and slow resource loads as spans for performance debugging.\n\n### Session Management\nSessions persist across page reloads via `sessionStorage` and automatically rotate after 30 minutes of inactivity.\n\n---\n\n## License\n\nThis SDK is licensed under the [MIT License](LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmonoscope-tech%2Fmonoscope-web","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmonoscope-tech%2Fmonoscope-web","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmonoscope-tech%2Fmonoscope-web/lists"}