Documentation

Server SDKs.

Capture events, people and errors from your servers, linked to the same visitors and sessions as your site.

Server SDKs

How server SDKs work

Send events from your backend with the same names, people and sessions as your site. Every SDK queues in memory, sends in batches in the background and never slows or breaks a request.

SettingValue
HostYour project's tracking hostname, such as https://m.example.com, from Setup
KeyA secret key (msk_) from Keys on the Setup page. Keep it on the server, never in page source.
BatchesUp to 50 events or every 5 seconds, retried with the same event ids so nothing is counted twice
ShutdownCall shutdown when your process stops, or flush at the end of a serverless function

Every SDK has the same calls, named in each language's style. capture, identify, alias, set, set_once, unset, group_identify, capture_exception, register, flags and flag, opt_out and opt_in, flush and shutdown.

Mode serves its SDKs itself, not from a public package registry, so each language below installs from Mode's own address. A published version never changes, and every file and its SHA-256 is listed in SHA256SUMS.

Logs, traces and AI calls. Send them with any OpenTelemetry SDK to /v1/logs, /v1/traces and /v1/metrics on the same hostname, with your key as Authorization: Bearer. See OpenTelemetry.
Server SDKs

Requests and sessions

Add the middleware for your framework and every event captured while a request runs knows who made it and which visit it belongs to.

The middleware reads the visitor the browser snippet already stored in the _mode cookie, so a backend on the same site links its events to the visitor's session with no setup. It also adds the page address (secret parameters removed), the referrer, the browser and the route, method and path of the request. An argument you pass to capture always wins.

An API on another hostname

When your API is on another subdomain or domain, turn on tracing headers. The browser then sends X-Mode-Distinct-Id and X-Mode-Session-Id on its calls to the hosts you list, and the middleware reads them. Allow both headers in your API's CORS rules.

Turn them on for a site with no code change in Metrics setup, under Tracing headers, by listing the API's hostnames there. The API and MCP do the same with configure_source, tracing_headers: true and tracing_hosts. The snippet then starts with them on every page of the site. Or set them in the snippet itself, which wins over the setting.

javascript
mode.init('YOUR_INGEST_KEY', { tracing_headers: ['api.example.com'] })

tracing_headers: true adds them to calls on the page's own origin only.

Server SDKs

Crawlers and bots

Search crawlers, AI crawlers and scripts never run your snippet. The middleware records their requests so you see which pages they read.

Each request from a crawler, an AI agent, a feed reader or a script is sent as a $http_log event with its page, status and time. Images, scripts, fonts and other static files are left out. Mode classes and names each one, and your bot policy decides whether it counts. Bots are kept out of reports and billing unless you count them.

http_logsWhat is sent
bots (default)Requests from crawlers, agents and scripts
allEvery request, people as $http_request, bots as $http_log
offNothing
Server SDKs

Location

Your server's location is not your visitors', so server events store no location by default.

Pass geoip: true to the client, or to one capture, for an event whose location should be kept. Events your site's snippet sends keep the visitor's location as always.

Server SDKs

Serverless functions

A function can stop as soon as it answers, so send what is queued before it returns.

Call flush (await it) before returning, or hand it to waitUntil where the platform has one, such as Cloudflare Workers and Vercel. Long running servers need only shutdown when the process stops.

Server SDKs

OpenTelemetry

Any OpenTelemetry SDK sends logs, traces, metrics and LLM calls to Mode Metrics with no Mode SDK.

Point the exporter at your tracking hostname over OTLP HTTP, protobuf or JSON, with your secret key. An exception recorded on a span or a log appears in Errors. A span that names a model is an LLM call, priced from its tokens. Set mode.distinct_id (or user.id) and mode.session_id on a span or log to tie it to a person and a visit.

shell
OTEL_EXPORTER_OTLP_ENDPOINT=https://m.example.com
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer YOUR_SECRET_KEY"

Logs, spans and data points are kept 14 days, or fewer if you choose. Longer is on Enterprise, see Data retention.

Server SDKs

Node.js

Capture server events, identities, bot traffic and errors across Node.js, Bun, Deno and serverless runtimes.

Install

shell
echo "@gotmode:registry=https://gotmode.com/sdk/npm/" >> .npmrc
npm install @gotmode/metrics-node

The .npmrc line sends every @gotmode package to Mode, so commit it with the project. pnpm, Yarn 1, Bun and Deno read it too.

FileVersionSHA-256
gotmode-metrics-node-0.1.0.tgz0.1.06dfadfb61ed163b3e6e9548fe56f3729791da16c542bf5a06e4336b936d4f3e0

Initialize, capture and identify

typescript
import { Mode } from '@gotmode/metrics-node'

const mode = new Mode(process.env.MODE_SECRET_KEY, {
  host: process.env.MODE_HOST,
  release: process.env.MODE_RELEASE,
})
mode.capture('user_42', 'order_paid', { amount: 1200 })
mode.identify('user_42', { set: { plan: 'pro' } }, 'browser_id')
mode.groupIdentify('company', 'acme', { set: { seats: 12 } }, 'user_42')
mode.unset('user_42', ['trial_ends'])
const enabled = await mode.flag('checkout', 'user_42')

Use the project tracking hostname and a secret key on the server. Secret URL parameters and email addresses are cleaned before delivery. Set http_logs to bots, all or off. GeoIP is off by default. Opt out with mode.optOut() until capture is permitted.

Bun

typescript
import { Mode } from '@gotmode/metrics-node'
const mode = new Mode(Bun.env.MODE_SECRET_KEY, { host: Bun.env.MODE_HOST })
mode.capture('user_42', 'job_completed')
await mode.shutdown()

Deno

typescript
import { Mode } from 'npm:@gotmode/metrics-node'
const mode = new Mode(Deno.env.get('MODE_SECRET_KEY'), {
  host: Deno.env.get('MODE_HOST'), exit_hooks: false,
})
mode.capture('user_42', 'job_completed')
await mode.shutdown()

Grant Deno environment access and network access to the tracking hostname. Both runtimes use the same capture and request scope API.

Framework and platform packages

Each integration below is its own package that depends on the core, so a server installs only the code it runs. Install the one you use next to @gotmode/metrics-node.

FileVersionSHA-256
gotmode-metrics-express-0.1.0.tgz0.1.024ee5ab57b8cae4e4fcc3f18c4c582b00745706e15e7b582c659de3c6969dcaf
gotmode-metrics-fastify-0.1.0.tgz0.1.03ac8a67f48f86552e11e256fabe221605a2e136364008064dccf65fd051e42a8
gotmode-metrics-koa-0.1.0.tgz0.1.04ca6686e1e048b7ae6bd71a268db33b4d72d3b31485878f7f0eba4a38424dc9a
gotmode-metrics-hono-0.1.0.tgz0.1.0404cb865c4ba8eb7fdc0434e5992b48780786a6196436a295822dff0228a5be6
gotmode-metrics-nestjs-0.1.0.tgz0.1.07f9a0632bf9d5535d5b713e9f234f55de645b2ba347b3f51c93f79bd1856e107
gotmode-metrics-workers-0.1.0.tgz0.1.03972385d960bad3e04bff6d50f959126ee8ea3d403bb96b383b002a416267a68
gotmode-metrics-vercel-0.1.0.tgz0.1.0814341d4ac15b66759eed2ddabe54f0a2bcc88d612cd4bd2fb1d7757bc47f5e0
gotmode-metrics-ai-sdk-0.1.0.tgz0.1.0718d40fc789888950a8909ae4716ace3f1d66ecc7e7776b40751fe7d2179511c
gotmode-metrics-convex-0.1.0.tgz0.1.02a2c26ea72af2707b17a49ed8686f1a7a630e47dc0c42f8eb17a38fd9654802f

Set trust_proxy only when your ingress overwrites forwarding headers. Use exclude_paths for health routes.

Express and Connect

Install the middleware before your routes and the error handler after them. Express route names include the router base path. Connect has no route templates.

shell
npm install @gotmode/metrics-express
typescript
import { modeMiddleware, modeErrorHandler } from '@gotmode/metrics-express'

app.use(modeMiddleware(mode))
app.get('/orders/:id', async (req, res) => {
  mode.capture(undefined, 'order_read')
  res.send('ok')
})
app.use(modeErrorHandler(mode))

For Connect, import connectMiddleware and connectErrorHandler from the same package and pass them to app.use before and after your handlers.

Fastify

shell
npm install @gotmode/metrics-fastify
typescript
import { modePlugin } from '@gotmode/metrics-fastify'

await app.register(modePlugin, { mode })
app.get('/orders/:id', async () => {
  mode.capture(undefined, 'order_read')
  return 'ok'
})

The plugin installs request, response and error hooks. Routes come from request.routeOptions.url.

Koa

shell
npm install @gotmode/metrics-koa
typescript
import { modeMiddleware } from '@gotmode/metrics-koa'

app.use(modeMiddleware(mode))
app.use(async ctx => {
  mode.capture(undefined, 'request_handled')
  ctx.body = 'ok'
})

Routers that expose _matchedRoute provide the route template.

Hono

shell
npm install @gotmode/metrics-hono
typescript
import { modeMiddleware } from '@gotmode/metrics-hono'

app.use(modeMiddleware(mode))
app.get('/orders/:id', ctx => {
  mode.capture(undefined, 'order_read')
  return ctx.text('ok')
})

Routes come from c.req.routePath. Edge deployments flush through c.executionCtx.waitUntil when available.

NestJS

shell
npm install @gotmode/metrics-nestjs
typescript
import { Module } from '@nestjs/common'
import { ModeModule } from '@gotmode/metrics-nestjs'

@Module({
  imports: [ModeModule.forRoot({ mode })],
})
export class AppModule {}

The module adds a global interceptor and exception filter. It reads controller and handler paths and preserves the framework's exception response. Inject MODE_METRICS to use the client from a provider.

Cloudflare Workers

shell
npm install @gotmode/metrics-workers
typescript
import { Mode } from '@gotmode/metrics-node'
import { withMode } from '@gotmode/metrics-workers'

export default {
  fetch(request, env, ctx) {
    const mode = new Mode(env.MODE_KEY, { host: env.MODE_HOST, flush_interval: 0, exit_hooks: false })
    return withMode(async () => {
      mode.capture(undefined, 'request_handled')
      return new Response('ok')
    }, { mode })(request, env, ctx)
  },
}

Enable nodejs_compat for asynchronous request scope. Without AsyncLocalStorage, use a client from mode.bindContext(scope) when carrying a scope across await. The wrapper passes the flush promise to ctx.waitUntil and records bot traffic.

Vercel Functions

shell
npm install @gotmode/metrics-vercel
typescript
import { withMode } from '@gotmode/metrics-vercel'

export default withMode(async (request, response) => {
  mode.capture(undefined, 'request_handled')
  response.end('ok')
}, { mode })

On Vercel the flush goes to the platform's waitUntil, with no other package to install. For another serverless entry point, await mode.flush() before returning, or pass it to the platform's own waitUntil.

Vercel AI SDK

Use AI SDK 7 with its version 4 language model middleware interface.

shell
npm install @gotmode/metrics-ai-sdk
typescript
import { wrapLanguageModel } from 'ai'
import { modeLanguageModelMiddleware } from '@gotmode/metrics-ai-sdk'

const model = wrapLanguageModel({
  model: providerModel,
  middleware: modeLanguageModelMiddleware(mode),
})

Every generation and completed or failed stream queues one OpenTelemetry LLM span. It carries model names, operation, tokens, cache tokens when reported, status, duration and the request's visitor and session. It goes to /v1/traces through the client's normal delivery queue. Prompts and output are excluded unless capture_content is true. Flush after consuming a stream in a short lived function.

typescript
modeLanguageModelMiddleware(mode, { capture_content: true })

Convex

Actions can make network calls. Wrap an action handler to flush before its result returns.

shell
npm install @gotmode/metrics-convex
typescript
import { action, httpAction } from './_generated/server'
import { withModeAction, withModeHttpAction } from '@gotmode/metrics-convex'

export const track = action({
  args: {},
  handler: withModeAction(mode, async (ctx, args, client) => {
    client.capture('user_42', 'action_completed')
  }),
})

export const endpoint = httpAction(withModeHttpAction(mode, async (ctx, request) => {
  mode.capture(undefined, 'request_handled')
  return new Response('ok')
}))

Mutations cannot fetch. Schedule an internal action with the event name, visitor id and properties through ctx.scheduler.runAfter(0, internal.metrics.capture, event). In that action, call mode.capture(event.distinct_id, event.event, event.properties) and await mode.flush(). Do not construct a capturing client or flush inside the mutation.

Flush and shutdown

typescript
await mode.flush()
await mode.shutdown(5)

The Node background timer does not keep the process alive. Node exit hooks flush automatically. Serverless handlers await flush or pass its promise to waitUntil. Events queue in memory with bounded retries. Logs, traces and model calls use the same tracking host through OpenTelemetry.

Server SDKs

Next.js

Capture browser activity, server events, request logs and errors across the app router, pages router and edge middleware.

Install

shell
echo "@gotmode:registry=https://gotmode.com/sdk/npm/" >> .npmrc
npm install @gotmode/metrics-next
FileVersionSHA-256
gotmode-metrics-next-0.1.0.tgz0.1.019b477c50974559cce1e967942d6048a6d35d72652063e51b9ede98ac8316aae
gotmode-metrics-node-0.1.0.tgz0.1.06dfadfb61ed163b3e6e9548fe56f3729791da16c542bf5a06e4336b936d4f3e0
gotmode-metrics-vercel-0.1.0.tgz0.1.0814341d4ac15b66759eed2ddabe54f0a2bcc88d612cd4bd2fb1d7757bc47f5e0

The package brings @gotmode/metrics-node and @gotmode/metrics-vercel with it. Its browser code carries the web SDK's core and none of its optional modules. Set NEXT_PUBLIC_MODE_HOST and NEXT_PUBLIC_MODE_KEY for the browser, and MODE_HOST and MODE_SECRET_KEY on the server. Browser capture goes directly to the tracking host.

App router provider and hooks

tsx
'use client'
import { ModeProvider, useMode, useFlag, useFlagPayload } from '@gotmode/metrics-next/client'

export function Providers({ children }) {
  return <ModeProvider tracing_headers>{children}</ModeProvider>
}

function Checkout() {
  const mode = useMode()
  const enabled = useFlag('checkout', false)
  const payload = useFlagPayload<{ label: string }>('checkout')
  return <button disabled={!enabled} onClick={() => {
    mode?.identify('user_42', { plan: 'pro' })
    mode?.capture('checkout_started')
  }}>{payload?.label ?? 'Checkout'}</button>
}

Render Providers inside the app layout. Initialization runs once. Pass consent and masking through options. Tracing headers are optional and restricted to same origin requests unless an explicit hostname list is supplied.

Server components, route handlers and server actions

typescript
import { getMode } from '@gotmode/metrics-next/server'

const mode = await getMode()
mode.capture(undefined, 'order_completed', { amount: 1200 })
mode.identify('user_42', { set: { plan: 'pro' }, unset: ['trial_end'] })
const enabled = await mode.flag('checkout')

The visitor comes from request headers and the shared cookie. Each returned client stays bound to that request. Delivery uses after() when available and otherwise waitUntil.

Edge middleware

typescript
import { withMode } from '@gotmode/metrics-next/middleware'
export default withMode()
// Or wrap the existing middleware as withMode(middleware).

Bot requests are logged by default and exceptions pass through unchanged. The edge event keeps the flush alive. A pass-through log describes the middleware response, before the downstream page has finished.

Pages router app

tsx
import { withModeApp } from '@gotmode/metrics-next/client'
export default withModeApp(App, { tracing_headers: true })

Pages API routes

typescript
import { configureMode, withModeApi } from '@gotmode/metrics-next/server'
const mode = configureMode(process.env.MODE_SECRET_KEY, { host: process.env.MODE_HOST })
export default withModeApi(async (req, res) => {
  mode.capture(undefined, 'api_called')
  res.status(200).json({ ok: true })
}, { route: '/api/orders/:id' })

Server side props

typescript
import { withModeServerSideProps } from '@gotmode/metrics-next/server'
export const getServerSideProps = withModeServerSideProps(async () => {
  return { props: {} }
}, { route: '/account' })

Pages wrappers provide request scope, capture exceptions and flush before returning. Props, redirects and responses retain their original behavior.

Source maps

typescript
import { withModeConfig } from '@gotmode/metrics-next/config'
export default withModeConfig({})

The upload command is a separate development package. It runs after the build and never ships with the app.

shell
npm install --save-dev @gotmode/metrics-next-sourcemaps
next build
npx mode-next-sourcemaps
FileVersionSHA-256
gotmode-metrics-next-sourcemaps-0.1.0.tgz0.1.0b87443a7f8984f9db68eb3a5c21b64bea8d492c8b0a98226db4942f4f84005d7

The command uses MODE_SECRET_KEY, a secret key with the metrics:source_maps permission, uploads every map to Mode's API with the build ID as its release, and respects rate limits. MODE_API_HOST or --host changes the API host. Use --dir and --asset-prefix when the build directory or asset URL differs. Configure error capture with the same release.

Flush and shutdown

typescript
await mode.flush()
// For a long lived custom server during shutdown.
await mode.shutdown()

Serverless helpers own their request flushes. Server events disable GeoIP by default. OpenTelemetry exporters and @gotmode/metrics-ai-sdk send logs, spans and model calls directly to the tracking host.

Server SDKs

Python

Capture from Python with a background thread or asyncio and request scope for Django, Flask, FastAPI, Starlette, ASGI and WSGI.

Each part is its own package, so an app installs only what it runs. Install the client, plus the one package for your framework.

requirements.txt
mode-metrics @ https://gotmode.com/sdk/python/mode-metrics/0.1.2/mode_metrics-0.1.2-py3-none-any.whl#sha256=e5bcd71a17bc8e05dd410ed46fbdc5ccb4e48132c6288e0b7316c28027cb71f2
mode-metrics-django @ https://gotmode.com/sdk/python/mode-metrics-django/0.1.2/mode_metrics_django-0.1.2-py3-none-any.whl#sha256=eb8e9f47c9e0637709ce417b89fd3826a7afd3a4ca744b88197dec2f6bb80ddb

pip checks each file against the SHA-256 in its address, and the version is fixed by the file. With python -m pip install the same lines go in quotes. Tools that read a package index can use https://gotmode.com/sdk/python/simple/ as the index for these packages, for example pip install --index-url https://gotmode.com/sdk/python/simple/ mode-metrics-flask, which brings the client and the WSGI middleware it builds on.

PackageForVersionSHA-256
mode-metricsThe event client. Every app that captures events0.1.2e5bcd71a17bc8e05dd410ed46fbdc5ccb4e48132c6288e0b7316c28027cb71f2
mode-metrics-djangoDjango middleware0.1.2eb8e9f47c9e0637709ce417b89fd3826a7afd3a4ca744b88197dec2f6bb80ddb
mode-metrics-flaskFlask extension, brings mode-metrics-wsgi0.1.2ed908367f5bbed659630689b39b75247604394a95feccb88e58f94aa2c74e7f3
mode-metrics-asgiFastAPI, Starlette and any ASGI app0.1.2025d70819730336017909bbcc3f528a90e873701c9c7757a06df775ee97c16ad
mode-metrics-wsgiAny WSGI app0.1.2c9a91a0527fa479c0103c904a89b19fea9746554e2d59a0af2c04abf1f87f081
python
from mode_metrics import Mode

metrics = Mode("YOUR_SECRET_KEY", host="https://m.example.com")
metrics.capture("user_42", "order_paid", {"total": 49})
metrics.identify("user_42", set={"plan": "team"}, anonymous_id="browser_42")
metrics.unset("user_42", ["trial_ends"])
metrics.shutdown(timeout=5)

Django

python
# settings.py
MODE_METRICS = {"key": "YOUR_SECRET_KEY", "host": "https://m.example.com"}
MIDDLEWARE = ["mode_metrics.django.ModeMiddleware", *MIDDLEWARE]

Flask

python
from mode_metrics.flask import Mode as FlaskMode
FlaskMode(app, client=metrics)

FastAPI, Starlette and ASGI

python
from mode_metrics.asgi import ModeMiddleware
app = ModeMiddleware(app, metrics)

WSGI

python
from mode_metrics.wsgi import ModeMiddleware
application = ModeMiddleware(application, metrics)

Inside a request, call metrics.capture(event="order_opened") to use the visitor and session from its headers or cookie. Middleware records bots by default, route templates, response status and raised exceptions.

Asyncio

python
from mode_metrics import AsyncMode

async def handle_job():
    metrics = AsyncMode("YOUR_SECRET_KEY", host="https://m.example.com")
    metrics.capture("user_42", "job_completed")
    await metrics.flush()
    await metrics.shutdown(timeout=5)
Server SDKs

Go

Send backend events with a standard library client, request scope and automatic bot logs for net/http, chi, gorilla, Gin and Echo.

The module path is on gotmode.com, which serves the module itself. Core needs Go 1.23 or newer.

shell
go get gotmode.com/sdk/go/metrics
FileVersionSHA-256
v0.1.0.zipv0.1.06b9f8b45daf2aa5654d3227378cd4c4a8bc9d7c991c37efafc12a53b43625389
v0.1.0.zipv0.1.007ed4260fd952368d5597d2c1fb88cd00408fa1a14a59e7710d1763ab0f33353
v0.1.0.zipv0.1.0d95e3ae65eb8deda41ff8ff8fffa45b25ce495c7c7a31cc6465a2b13e8ec499b
go
import metrics "gotmode.com/sdk/go/metrics"

client := metrics.New(os.Getenv("MODE_KEY"), metrics.Options{
    Host: os.Getenv("MODE_HOST"),
})
client.Capture("user_42", "order_completed", metrics.Properties{"total": 49})
client.Identify("user_42", metrics.PersonProperties{
    Set: metrics.Properties{"plan": "pro"},
    Unset: []string{"trial_ends"},
}, "browser_anonymous_id")

Import os for environment values. Keep the secret key on the server and use your project's tracking host.

net/http, chi and gorilla

go
mux := http.NewServeMux()
mux.HandleFunc("GET /users/{user}", func(w http.ResponseWriter, r *http.Request) {
    client.CaptureCtx(r.Context(), "", "profile_viewed", nil)
    w.WriteHeader(http.StatusNoContent)
})
handler := client.Middleware()(mux)

Import net/http. Wrap a chi or gorilla handler the same way and use MiddlewareOptions.Route to supply its route template. ServeMux uses r.Pattern. The middleware reads the browser cookie and tracing headers, records completed requests and captures panics before passing them on unchanged.

Gin

shell
go get gotmode.com/sdk/go/metrics/gin
go
import modegin "gotmode.com/sdk/go/metrics/gin"

router := gin.New()
router.Use(gin.Recovery(), modegin.Middleware(client))

Gin needs Go 1.25 or newer and imports github.com/gin-gonic/gin.

Echo

shell
go get gotmode.com/sdk/go/metrics/echo
go
import modeecho "gotmode.com/sdk/go/metrics/echo"

server := echo.New()
server.Use(middleware.Recover())
modeecho.Install(server, client)

Echo needs Go 1.26 or newer. Import github.com/labstack/echo/v4 and its middleware package. Configure your error handler before calling Install, which records its completed response.

Shutdown

go
// Stop accepting HTTP requests first.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = client.Close(ctx)

Import context and time. In a serverless function, call client.Flush(ctx) before returning. Flag lookups return buffered channels and default on failure. Use OptOut and OptIn to follow consent. GeoIP is disabled by default and request logs default to bots.

Server SDKs

Ruby

Queue Ruby events in a fork-safe worker and capture Rack and Rails requests, sessions and exceptions automatically.

Add Mode's gem source to your Gemfile for the Mode gems, then run bundle install. Add the line for your framework. mode_metrics-rails brings mode_metrics-rack, which brings the mode_metrics core, so each app installs only the code it runs.

ruby
source "https://gotmode.com/sdk/ruby" do
  gem "mode_metrics"
  gem "mode_metrics-rails" # Rails, or "mode_metrics-rack" for Sinatra, Hanami, Roda and other Rack apps
end

Without Bundler, run gem install mode_metrics-rails --source https://gotmode.com/sdk/ruby, or name mode_metrics-rack or mode_metrics.

FileVersionSHA-256
mode_metrics-0.1.0.gem0.1.0a8d35a4950aa77f8a5b2b6278ec1fba56c528498b8babc6fb9e1f436ded04376
mode_metrics-rack-0.1.0.gem0.1.09aa6011262752de93741fb91da30b222565e1fd716adb5bc22edd8930d32a9a5
mode_metrics-rails-0.1.0.gem0.1.0f5257e1da9c0b2b0778bedea9dbec8544a915acd203037715fdab4775fdbaeaf
ruby
require "mode_metrics"
metrics = ModeMetrics::Client.new(ENV["MODE_METRICS_KEY"], host: ENV["MODE_METRICS_HOST"])
metrics.capture("user_42", "order_placed", { total: 29 })
metrics.identify("user_42", { set: { plan: "pro" } }, "browser_42")
metrics.unset("user_42", ["trial_ends"])
metrics.shutdown(5)

The Rack middleware in mode_metrics-rack reads the Mode cookie and tracing headers. Calls within the request can pass nil for the distinct id.

ruby
# config.ru
require "mode_metrics/rack"
use ModeMetrics::Rack, client: metrics, exclude_paths: ["/health"]
run MyApplication

With mode_metrics-rails, Rails loads the middleware and error reporter subscriber through the Railtie. Set the environment variables or configure the application directly.

ruby
# config/application.rb
config.mode_metrics.key = ENV["MODE_METRICS_KEY"]
config.mode_metrics.host = ENV["MODE_METRICS_HOST"]
config.mode_metrics.http_logs = "bots"

# Inside a controller or service on this request
ModeMetrics.client.capture(nil, "order_placed")

Rails 7.1 and later supply route templates. The exit hook flushes within five seconds, and forked workers start their own sender on first use. In a serverless handler, call metrics.flush before returning.

Server SDKs

PHP

Queue events in PHP and add request identity, bot logs and exceptions with PSR-15 or Laravel.

Install

shell
composer config repositories.mode composer https://gotmode.com/sdk/composer
composer require gotmode/mode-metrics
composer require gotmode/mode-metrics-laravel   # Laravel, or gotmode/mode-metrics-psr15 for PSR-15

Composer takes the Mode packages from Mode's repository and everything else from Packagist as before. Each framework package depends on gotmode/mode-metrics, so an app without one installs only the core.

FileVersionSHA-256
gotmode-mode-metrics-0.1.0.zip0.1.0bc284959dc86232cb941802c4e891701f601d3ef7a74621e7d5ff23c3cd994fb
gotmode-mode-metrics-psr15-0.1.0.zip0.1.0dbed8d143c819d3b9468424eddfbce3fcdf52f54760ad2e615cc60532a92a043
gotmode-mode-metrics-laravel-0.1.0.zip0.1.0c97f5499c1af6b08dad3b1c6dbfefd14fd2c37006e982cfd99eb1825a3ff5b4b

Initialize and capture

php
use ModeMetrics\Client;

$metrics = new Client(getenv('MODE_METRICS_KEY'), [
    'host' => getenv('MODE_METRICS_HOST'),
]);
$metrics->capture('user_42', 'order_completed', ['total' => 29]);
$metrics->identify('user_42', ['set' => ['plan' => 'team']], 'browser_anonymous_id');

PSR-15

Require gotmode/mode-metrics-psr15, which brings psr/http-server-middleware, and add this middleware to its pipeline. Set the request's route_template attribute when the router exposes one.

php
$middleware = new ModeMetrics\Middleware($metrics, ['http_logs' => 'bots']);
$response = $middleware->process($request, $handler);

Laravel

Require gotmode/mode-metrics-laravel and Composer discovers the service provider and facade. Set MODE_METRICS_KEY and MODE_METRICS_HOST. The provider inserts the middleware, reads route templates and reports exceptions through Laravel's handler.

php
use ModeMetrics\Laravel\Facade as ModeMetrics;

ModeMetrics::capture(null, 'invoice_created', ['invoice_id' => 'invoice_42']);

Flush and shutdown

PHP batches in memory until explicit flush, Laravel termination or the shutdown hook. The hook finishes FastCGI responses before sending. Use an explicit flush at serverless and queue job boundaries. Flags and explicit flush wait for the network within their timeout.

php
$metrics->flush();
$metrics->shutdown(5);
Server SDKs

Java and the JVM

Capture from Java, Kotlin and Scala with a dependency free Java 11+ client, a Jakarta Servlet filter, and Spring Boot 3 integration on Java 17+.

Add Mode's Maven repository, then com.gotmode:mode-metrics, com.gotmode:mode-metrics-servlet or com.gotmode:mode-metrics-spring.

xml
<repositories>
  <repository><id>mode</id><url>https://gotmode.com/sdk/maven</url></repository>
</repositories>
<dependency>
  <groupId>com.gotmode</groupId>
  <artifactId>mode-metrics</artifactId>
  <version>0.1.0</version>
</dependency>
kotlin
// Gradle, settings.gradle.kts
dependencyResolutionManagement {
    repositories {
        mavenCentral()
        exclusiveContent {
            forRepository { maven("https://gotmode.com/sdk/maven") }
            filter { includeGroup("com.gotmode") }
        }
    }
}
// build.gradle.kts
dependencies { implementation("com.gotmode:mode-metrics:0.1.0") }
FileVersionSHA-256
mode-metrics-0.1.0.jar0.1.0e897f8ab6ec47410c0df9239ac8dca7a033b5f2ce1d9bc339708a52d5bd576d1
mode-metrics-servlet-0.1.0.jar0.1.0bed70a7f365a228d8ab867a0d80628d8eb1ae95786ed2e0afd9dab9a3cc26334
mode-metrics-spring-0.1.0.jar0.1.02a685ec399bc5f02a01d01bf86b6d9a9a05678585be54dcd0b529de26e76c6d5
java
import com.gotmode.metrics.*;
import java.util.Map;

Options options = new Options(System.getenv("MODE_METRICS_KEY"), System.getenv("MODE_METRICS_HOST"));
ModeMetrics metrics = new ModeMetrics(options);
metrics.capture("user_42", "order_paid", Map.of("amount", 29));
metrics.identify("user_42", Map.of("set", Map.of("plan", "team")), "browser_42");

Jakarta Servlet

Register the filter around your handlers and enable asynchronous dispatch. Pass null as the capture identity inside a request to use the visitor from its cookie or tracing headers.

java
import com.gotmode.metrics.servlet.ModeMetricsFilter;
import jakarta.servlet.DispatcherType;
import java.util.EnumSet;

var filter = servletContext.addFilter("modeMetrics", new ModeMetricsFilter(metrics));
filter.setAsyncSupported(true);
filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC), false, "/*");

Spring Boot

The Spring package installs a OncePerRequestFilter, captures route templates and exceptions, and flushes when the application stops. Set the application properties and inject ModeMetrics into your handlers.

properties
mode.metrics.key=${MODE_METRICS_KEY}
mode.metrics.host=${MODE_METRICS_HOST}
mode.metrics.http-logs=bots
java
// Before returning from a serverless invocation
metrics.flush().join();
// When the client is no longer needed
metrics.close();
Server SDKs

.NET

Capture backend events with the .NET client and connect ASP.NET Core requests to browser visitors and sessions.

Add Mode's package feed in a nuget.config next to your solution. The source mapping takes the Mode packages only from Mode, and every other package from nuget.org as before.

xml
<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
    <add key="mode" value="https://gotmode.com/sdk/nuget/index.json" />
  </packageSources>
  <packageSourceMapping>
    <packageSource key="mode"><package pattern="Mode.Metrics" /><package pattern="Mode.Metrics.*" /></packageSource>
    <packageSource key="nuget.org"><package pattern="*" /></packageSource>
  </packageSourceMapping>
</configuration>
shell
dotnet add package Mode.Metrics
dotnet add package Mode.Metrics.AspNetCore
FileVersionSHA-256
mode.metrics.0.2.0.nupkg0.2.0e6844e09cb6cd4dd5aacd7e2fb961f694a7cbe4b91e6658ef9febafe41a93565
mode.metrics.aspnetcore.0.2.0.nupkg0.2.0b1f65c077c877509f097579fc453e3833a4f4bf0d1824027f7cb016ba2ba5a72
csharp
using Mode.Metrics;

await using var metrics = new MetricsClient(new MetricsOptions
{
    Key = Environment.GetEnvironmentVariable("MODE_METRICS_KEY") ?? "",
    Host = Environment.GetEnvironmentVariable("MODE_METRICS_HOST") ?? ""
});
metrics.Capture("user_42", "order_placed", new { total = 49 });
metrics.Identify("user_42", new PersonProperties
{
    Set = new { plan = "team" },
    Unset = ["trial_ends"]
}, anonymousId: "browser_42");
await metrics.FlushAsync();
await metrics.ShutdownAsync(TimeSpan.FromSeconds(5));

ASP.NET Core

Set ModeMetrics__Key and ModeMetrics__Host in your environment. The integration also reads the ModeMetrics configuration section and flushes when the host stops.

csharp
using Mode.Metrics;
using Mode.Metrics.AspNetCore;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddModeMetrics();
var app = builder.Build();
app.UseRouting();
app.UseModeMetrics();
app.MapGet("/orders/{orderId}", (string orderId, MetricsClient metrics) =>
{
    // The request scope supplies the visitor and session
    metrics.Capture(null, "order_viewed", new { order_id = orderId });
    return Results.Ok();
});
app.Run();

Bot logs and exception capture run automatically. Set HttpLogs to all or off to change request logging. Server events disable location by default. In serverless handlers, await FlushAsync() before returning.

Server SDKs

Elixir

A supervised queue sends events in background Tasks, with Plug and Phoenix request scopes, bot logs and exception capture.

Mode serves its own Hex repository. Add it once on each machine and build server. Mix downloads its public key and checks it against this fingerprint. Needs Hex 2.0 or newer.

shell
mix hex.repo add gotmode https://gotmode.com/sdk/hex --fetch-public-key SHA256:EHzJp0NYVLNKpASnvzJ6+DdKYP3KODsJp5ymX+zCDcs

Then add the packages to your deps and run mix deps.get. mode_metrics_plug is for Plug and Phoenix and brings Plug.

elixir
# mix.exs
{:mode_metrics, "~> 0.1.0", repo: "gotmode"},
{:mode_metrics_plug, "~> 0.1.0", repo: "gotmode"}  # Plug and Phoenix

The key is also at gotmode.com/sdk/hex/public_key for --public-key.

FileVersionSHA-256
mode_metrics-0.1.0.tar0.1.0c04ab6da7d2ea317bf1cb1887908a85908e245bab459691ec36099aace354370
mode_metrics_plug-0.1.0.tar0.1.068a2c8c5e7d00378713a0946a783151a5d394b533c3892e5746a426fc66fd730
elixir
# Add to your application's supervision children
{ModeMetrics,
  key: System.fetch_env!("MODE_METRICS_KEY"),
  host: System.fetch_env!("MODE_METRICS_HOST")}

ModeMetrics.capture("user_42", "order_paid", %{"total" => 49})
ModeMetrics.identify("user_42", %{set: %{"plan" => "team"}}, "browser_42")
ModeMetrics.unset("user_42", ["trial_ends"])
ModeMetrics.shutdown(5000)

Plug

elixir
defmodule MyApp.Router do
  use Plug.Router
  use ModeMetrics.Plug
  plug :match
  plug ModeMetrics.Plug, http_logs: "bots"
  plug :dispatch
end

The use ModeMetrics.Plug wrapper captures raised exceptions and restores scope. A plain pipeline step cannot catch exceptions from later steps. A generic outer wrapper can instead use plug ModeMetrics.Plug, plug: MyApp.Router.

Phoenix

elixir
# In the endpoint module, after use Phoenix.Endpoint
use ModeMetrics.Plug

# In a router pipeline
plug ModeMetrics.Plug

Capture with ModeMetrics.capture(nil, "order_opened") inside a request to use its visitor and session. The middleware reads the Mode cookie and headers, adds the route template and records response status. Durations use milliseconds. Call ModeMetrics.flush() before a short lived function returns, or ModeMetrics.shutdown(5000) when stopping explicitly.

Server SDKs

Rust

Capture backend events with a bounded background worker and add request context through the axum Tower layer.

Add Mode's registry to .cargo/config.toml in your project, then name it on the dependency.

toml
# .cargo/config.toml
[registries.mode]
index = "sparse+https://gotmode.com/sdk/cargo/index/"
FileVersionSHA-256
mode-metrics-0.1.0.crate0.1.0ce35e47ad922cfb3f9419019ee32f2072ffd89d2cd3881e412b1c437667968c2
toml
# Cargo.toml
[dependencies]
mode-metrics = { version = "0.1.0", registry = "mode", features = ["axum"] }
serde_json = "1"
axum = "0.8"
rust
use mode_metrics::{CaptureOptions, Client, Config, PersonProperties};
use serde_json::json;
use std::time::Duration;

let metrics = Client::new("YOUR_SECRET_KEY", Config {
    host: "https://m.example.com".into(),
    ..Default::default()
});
metrics.capture("user_42", "purchase", json!({"amount": 49}), CaptureOptions::default());
metrics.identify("user_42", PersonProperties {
    set: json!({"plan": "pro"}).as_object().cloned(),
    ..Default::default()
}, Some("browser_42"));

axum and Tower

rust
use axum::{routing::get, Router};
use mode_metrics::axum::MetricsLayer;

let handler_metrics = metrics.clone();
let app = Router::new()
    .route("/orders/{id}", get(move || {
        let metrics = handler_metrics.clone();
        async move {
            metrics.capture_ctx("order_read", json!({}), CaptureOptions::default());
            "ok"
        }
    }))
    .layer(MetricsLayer::new(metrics.clone()));

The layer reads the browser cookie and tracing headers, records bot requests and captures handler exceptions. Enable the tokio feature and select Worker::Tokio for reqwest with rustls. The default worker uses a standard thread and ureq.

rust
// Before a serverless function returns
metrics.flush(Duration::from_secs(5));
// When the server stops
metrics.shutdown(Duration::from_secs(5));

Let AI run your marketing.

Mode Agent does the daily work. You approve the spend.

Get early access