User Dashboard Domain Realtime Delivery, Telemetry Hooks, and Frontend Observability

Overview

This feature area wires the browser dashboard runtime to three operational concerns that stay outside the application submission flow: tracing, realtime transport, and service health. The Next.js runtime registers OpenTelemetry and Sentry at boot, the browser runtime initializes Sentry with replay and router-transition capture, and the realtime client opens a singleton EventSource for dashboard-delivery streams.

The user-visible impact is that dashboard-adjacent pages can participate in span collection, capture route transitions, and receive live updates without embedding observability or stream bootstrap logic into submission screens. The health endpoint exposes a lightweight backend reachability check for platform probes and operators, while the telemetry hooks apply across the App Router runtime.

Architecture Overview

flowchart TB
    subgraph BrowserRuntime [Browser Runtime]
        DashboardPages[Dashboard Adjacent Pages]
        SentryClient[instrumentation-client ts]
        RealtimeClient[ably-client ts]
        RouterTransitions[Router Transition Capture]
    end

    subgraph NextRuntime [Next.js Server Runtime]
        Instrumentation[instrumentation ts]
        HealthRoute[health route]
    end

    subgraph ExternalServices [External Services]
        Sentry[Sentry]
        OpenTelemetry[OpenTelemetry Exporter]
        BackendHealth[Backend Health Endpoint]
        RealtimeStream[Realtime Event Stream]
    end

    DashboardPages --> RouterTransitions
    RouterTransitions --> SentryClient
    DashboardPages --> RealtimeClient

    SentryClient --> Sentry
    Instrumentation --> OpenTelemetry
    Instrumentation --> SentryClient
    Instrumentation --> Sentry

    RealtimeClient --> RealtimeStream
    HealthRoute --> BackendHealth
    HealthRoute --> OpenTelemetry

Component Structure

1. Telemetry Registration

instrumentation.ts (frontend/instrumentation.ts)

This module registers runtime telemetry for the Next.js server process. It derives the OpenTelemetry service name from OTEL_SERVICE_NAME and loads the Sentry server or edge configuration based on NEXT_RUNTIME.

Public methods

Method Description
register Registers OpenTelemetry with the computed service name and conditionally imports sentry.server.config or sentry.edge.config based on runtime.

Module state

Property Type Description
serviceName string OpenTelemetry service name resolved from OTEL_SERVICE_NAME or the default lita-frontend.

Behavior

  • Calls registerOTel({ serviceName }) once the runtime starts.
  • Imports ./sentry.server.config when NEXT_RUNTIME === "nodejs".
  • Imports ./sentry.edge.config when NEXT_RUNTIME === "edge".

instrumentation-client.ts (frontend/instrumentation-client.ts)

This module initializes browser-side Sentry for dashboard flows. It enables tracing, replay, and transition capture when a DSN is configured.

Public symbols

Symbol Description
onRouterTransitionStart Exports Sentry.captureRouterTransitionStart so App Router transitions can be captured by Sentry.

Telemetry configuration

Setting Source Effect
dsn NEXT_PUBLIC_SENTRY_DSN or SENTRY_DSN Enables the browser Sentry SDK when present.
environment NEXT_PUBLIC_SENTRY_ENVIRONMENT or NODE_ENV Tags events with the current environment.
enabled Boolean(dsn) Disables Sentry when no DSN is configured.
tracesSampleRate NEXT_PUBLIC_SENTRY_TRACES_SAMPLE_RATE or 0.1 Controls tracing sample rate.
replaysSessionSampleRate NEXT_PUBLIC_SENTRY_REPLAYS_SESSION_SAMPLE_RATE or 0 Controls session replay sampling.
replaysOnErrorSampleRate NEXT_PUBLIC_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE or 1 Controls replay capture after errors.
integrations Sentry.replayIntegration() Enables replay integration in the browser.
debug NODE_ENV === "development" Enables development-time Sentry debug logging.

Initialization behavior

  • Runs Sentry.init(...) at module load time.
  • Uses browser-only configuration via @sentry/nextjs.
  • Routes transition capture is exported separately through onRouterTransitionStart.

2. Realtime Delivery Client

ably-client.ts (frontend/lib/realtime/ably-client.ts)

This client centralizes browser-side realtime stream creation behind a singleton EventSource. It is a client-only helper that resolves the stream URL from NEXT_PUBLIC_REALTIME_EVENTS_URL or falls back to the application origin plus /api/v1/applications/stream.

Public methods

Method Description
getAblyClient Returns the shared browser EventSource instance for realtime delivery or null on the server.

Module state

Property Type Description
singletonEventSource `EventSource \ null`

Connection lifecycle

  1. Server-side execution returns null immediately.
  2. The first browser call resolves the stream URL.
  3. A new EventSource is created and stored in singletonEventSource.
  4. Later calls return the same instance.

Data flow

  • NEXT_PUBLIC_REALTIME_EVENTS_URL is used when present and non-empty.
  • Otherwise the client connects to ${window.location.origin}/api/v1/applications/stream.
  • Realtime consumers subscribe to the browser EventSource message stream.

Sequence diagram

sequenceDiagram
    participant Page as Dashboard Page
    participant Client as getAblyClient
    participant Browser as EventSource
    participant Stream as Realtime Event Stream

    Page->>Client: getAblyClient
    Client->>Client: resolve stream url
    Client->>Browser: create EventSource
    Browser->>Stream: connect
    Stream-->>Browser: message events
    Browser-->>Page: message callbacks

3. Health Check Proxy

(frontend/app/api/health/route.ts)

This route proxies health checks to the backend API. It sanitizes the configured backend base URL, fetches ${backendBaseUrl}/health with cache: "no-store", and forwards either the backend payload or a structured error response.

Public methods

Method Description
GET Proxies a health check to the backend API and returns the backend response or a structured error.

Behavior

  • Reads NEXT_PUBLIC_BACKEND_API_URL first, then BACKEND_API_URL.
  • Trims trailing slashes before building the backend health URL.
  • Returns a 500 response when no backend base URL is configured.
  • Returns the backend status code and detail text when the backend health response is not OK.
  • Returns 502 when the backend health request cannot be completed.

Health Check Endpoint

{
    "title": "Health Check Proxy",
    "description": "Proxies the backend health endpoint for frontend readiness and operational checks",
    "method": "GET",
    "baseUrl": "<FrontendBaseUrl>",
    "endpoint": "/api/health",
    "headers": [],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Backend health payload forwarded by the frontend route",
            "body": "{\n    \"ok\": true\n}"
        },
        "500": {
            "description": "Backend base URL is missing",
            "body": "{\n    \"detail\": \"Backend API URL is not configured.\"\n}"
        },
        "502": {
            "description": "Backend health check could not be reached",
            "body": "{\n    \"detail\": \"Failed to reach backend API. Connection refused\"\n}"
        }
    }
}

Feature Flows

1. Dashboard Runtime Telemetry Bootstrap

The App Router runtime activates OpenTelemetry first, then loads the correct Sentry server or edge configuration. Browser pages then initialize the client Sentry SDK and wire router transitions into Sentry tracing.

sequenceDiagram
    participant Runtime as Next.js Runtime
    participant OTel as registerOTel
    participant SentryServer as sentry server config
    participant SentryEdge as sentry edge config
    participant Browser as Dashboard Page
    participant SentryClient as Sentry Browser SDK

    Runtime->>OTel: register serviceName
    Runtime->>SentryServer: import when nodejs
    Runtime->>SentryEdge: import when edge
    Browser->>SentryClient: initialize browser telemetry
    Browser->>SentryClient: capture router transition start
    SentryClient-->>Browser: route transition trace

2. Realtime Stream Bootstrap and Message Delivery

Dashboard-adjacent UI can resolve a shared EventSource through getAblyClient, which creates the browser stream connection once and reuses it for later calls.

sequenceDiagram
    participant User as User
    participant Page as Dashboard Page
    participant Client as getAblyClient
    participant Source as EventSource
    participant Stream as Realtime Event Stream

    User->>Page: open dashboard flow
    Page->>Client: getAblyClient
    Client->>Client: compute stream url
    Client->>Source: create singleton stream
    Source->>Stream: connect
    Stream-->>Source: realtime event
    Source-->>Page: event callback
    Page-->>User: UI update

3. Health Check Request Path

The frontend health route acts as a thin proxy over backend health state. It is useful for probes and operational visibility without involving application submission data.

sequenceDiagram
    participant Probe as Platform Probe
    participant Frontend as frontend app api health
    participant Backend as Backend API health

    Probe->>Frontend: GET /api/health
    Frontend->>Backend: GET /health
    Backend-->>Frontend: health payload or error
    Frontend-->>Probe: proxied JSON response

State Management

Module-Level Runtime State

State Scope Purpose
serviceName instrumentation.ts module Sets the OpenTelemetry service name for the frontend runtime.
singletonEventSource ably-client.ts module Reuses one browser realtime connection across consumers.
enabled instrumentation-client.ts Sentry init Enables browser telemetry only when a DSN exists.

Runtime Guards

  • getAblyClient returns null on the server by checking typeof window === "undefined".
  • instrumentation.ts branches on NEXT_RUNTIME to import the correct Sentry runtime config.
  • health/route.ts sanitizes the backend base URL before any fetch occurs.

Integration Points

  • Sentry browser tracing via @sentry/nextjs.
  • Sentry replay via Sentry.replayIntegration().
  • OpenTelemetry registration via @vercel/otel.
  • Backend health endpoint via ${BACKEND_API_URL}/health.
  • Realtime event stream via EventSource and /api/v1/applications/stream.
  • App Router transition capture via Sentry.captureRouterTransitionStart.

Analytics and Tracking

Tracing and Observability Signals

  • Browser route transitions captured by onRouterTransitionStart.
  • Browser error and replay collection through Sentry replay integration.
  • Runtime spans registered through registerOTel.
  • Server and edge Sentry configuration loaded by runtime.

Configuration Inputs

Variable Used By Purpose
NEXT_PUBLIC_SENTRY_DSN instrumentation-client.ts Browser Sentry DSN.
SENTRY_DSN instrumentation-client.ts Server or shared Sentry DSN fallback.
NEXT_PUBLIC_SENTRY_ENVIRONMENT instrumentation-client.ts Browser Sentry environment tag.
NEXT_PUBLIC_SENTRY_TRACES_SAMPLE_RATE instrumentation-client.ts Browser trace sampling.
NEXT_PUBLIC_SENTRY_REPLAYS_SESSION_SAMPLE_RATE instrumentation-client.ts Browser session replay sampling.
NEXT_PUBLIC_SENTRY_REPLAYS_ON_ERROR_SAMPLE_RATE instrumentation-client.ts Browser replay sampling after errors.
OTEL_SERVICE_NAME instrumentation.ts OpenTelemetry service name.
NEXT_PUBLIC_REALTIME_EVENTS_URL ably-client.ts Overrides the realtime stream URL.
NEXT_PUBLIC_BACKEND_API_URL health/route.ts Backend base URL for health proxy.
BACKEND_API_URL health/route.ts Backend base URL fallback for health proxy.
NEXT_RUNTIME instrumentation.ts Selects server or edge Sentry config.
NODE_ENV instrumentation-client.ts Controls debug mode and environment fallback.

Error Handling

instrumentation-client.ts

  • Disables the browser SDK when no DSN is configured by setting enabled: Boolean(dsn).
  • Uses debug: process.env.NODE_ENV === "development" to keep verbose output in development only.

ably-client.ts

  • Returns null when executed outside the browser.
  • Reuses the existing singleton stream when already created.

health/route.ts

  • Returns 500 when neither backend URL variable is configured.
  • Returns the backend status code and a detail message when the backend health endpoint responds with an error.
  • Returns 502 when the fetch itself throws.

Caching Strategy

Observability and Realtime

Method Cache Behavior Notes
register None Boot-time registration only.
getAblyClient Singleton memoization Keeps one browser EventSource instance in module state.
GET in health/route.ts no-store Always fetches the current backend health state.

Runtime Fetch Options

  • health/route.ts uses cache: "no-store" for backend health calls.
  • Browser Sentry and OpenTelemetry hooks are initialized without application-level data caching.

Dependencies

Runtime Packages

  • @sentry/nextjs
  • @vercel/otel

Browser and Platform APIs

  • EventSource
  • window.location.origin
  • process.env.NEXT_RUNTIME
  • process.env.NODE_ENV

External Services

  • Sentry ingestion and replay services
  • OpenTelemetry export endpoint
  • Backend /health
  • Realtime stream endpoint at /api/v1/applications/stream

Testing Considerations

  • Verify instrumentation-client.ts only enables Sentry when a DSN is present.
  • Verify onRouterTransitionStart is exported and wired to Sentry.captureRouterTransitionStart.
  • Verify register() loads sentry.server.config for nodejs and sentry.edge.config for edge.
  • Verify getAblyClient() returns null on the server and a singleton EventSource in the browser.
  • Verify health/route.ts returns 500 when backend base URL env vars are missing.
  • Verify health/route.ts forwards the backend payload on success and preserves backend error status codes on failure.

Key Classes Reference

Class Responsibility
instrumentation.ts Registers OpenTelemetry and loads the correct Sentry runtime configuration.
instrumentation-client.ts Initializes browser Sentry tracing, replay, and router-transition capture.
ably-client.ts Provides the singleton browser realtime stream client.
health/route.ts Proxies backend health checks for frontend operational visibility.