@lntrn/device
v1.3.0
Published
Lantern's device SDK — send logs, metrics and analytics events from anything that runs JavaScript.
Readme
@lntrn/device
Send logs, metrics and analytics events to Lantern from anything that runs JavaScript — browsers, Node, Deno, Bun, React Native, Cloudflare Workers.
Records go to Lantern as OTLP/HTTP JSON — the standard OpenTelemetry
endpoints, POST /v1/logs and POST /v1/metrics — since 1.0.0. Earlier
versions sent Lantern's own device format to POST /v1/ingest, which the
ingest no longer accepts; the API is the same, so upgrading is a version
bump. See CHANGELOG.md.
Formerly @xeonr/forest; the CHANGELOG's 0.5.0 entry has the
import-by-import migration.
Already on OpenTelemetry? Add this
Keep your SDK and exporters. Add @lntrn/device/otel for the device token
and, optionally, this package's API over your providers:
import { deviceTokenHeaders, OtelLantern, INGEST_URL } from "@lntrn/device/otel";
// One factory for every exporter, so they share one token. It is cached
// until shortly before its exp, then fetched again.
const headers = deviceTokenHeaders(() => fetch("/api/device-token").then((r) => r.text()));
new OTLPTraceExporter({ url: `${INGEST_URL}/v1/traces`, headers });
new OTLPLogExporter({ url: `${INGEST_URL}/v1/logs`, headers });
new OTLPMetricExporter({ url: `${INGEST_URL}/v1/metrics`, headers });
// Optional: lantern.info / error / metric / event, through your providers.
const lantern = new OtelLantern({ loggerProvider, meterProvider });
lantern.error(err, { route: "/player", sessionId });The exporters are the stock @opentelemetry/exporter-{trace,logs,metrics}-otlp-{proto,http}
(0.300). Each takes headers as an async function and calls it before every
export.
The token cache
deviceTokenHeaders wraps your token source in a TokenCache:
- it reads the JWT's
expand renews a minute before it, or at four fifths of the lifetime for a shorter token; - concurrent exports share one fetch;
- a failed fetch keeps the old token while it is still valid;
- with no token at all, the export goes without a header and
onErroris told.
The source can be mintToken from @lntrn/device/server, on a server that
holds the key.
What OtelLantern sends
Records have the same shape as the standalone client's, so fields, Issues and dashboards read them the same:
- errors carry
exception.*; - events are INFO records with
event.name/event.value; - metrics with
kind: "counter"are OTel counters, and withkind: "histogram"real histograms.
Batching, retries and the hide-time flush are your processors' and readers' business, not this class's.
What the ingest stamps
The token decides the project. Whatever your resource says, the ingest sets:
- the project's service and environment;
service.instance.idfrom the token's client id;- any attributes pinned to the token.
No identity processor is needed.
What this entry pulls in
@lntrn/device/otel imports OpenTelemetry for types only. @opentelemetry/api
and @opentelemetry/api-logs are optional peer dependencies, and the default
entry still has no dependencies at all.
Without OpenTelemetry
Zero dependencies. One class.
import { Lantern } from "@lntrn/device";
const lantern = new Lantern({ token });
lantern.info("user signed in");
lantern.error(new Error("upload failed"));
lantern.metric("fps", 59.5);
lantern.event("checkout_completed", { plan: "pro" });
// counters, units and event values take the full-record form
lantern.addMetric({ name: "frames.dropped", value: 3, kind: "counter", unit: "1" });
lantern.addEvent({ name: "playback.stop", value: 41.2 });That's the whole API. Records are queued and sent in batches in the background;
nothing blocks and nothing throws — a telemetry client that can break the
application it observes is worse than no telemetry. Delivery problems go to
onError.
Getting a token
A device never holds your API key. Your backend holds it and hands out short-lived per-device tokens:
// server-side only
import { mintToken } from "@lntrn/device/server";
app.get("/telemetry-token", async (req, res) => {
const token = await mintToken({
apiKey: process.env.LANTERN_DEVICE_KEY!, // fk_<id>_<secret>
clientId: req.user.deviceId, // your own id for this device
ttlSeconds: 3600,
attrs: { plan: req.user.plan }, // stamped on every record
});
res.json({ token });
});Minting lives at @lntrn/device/server — a separate entry point so it
can never be pulled into a browser bundle by accident. Never ship your API
key to a device.
Tokens expire, so pass a function and the client refreshes on its own:
const lantern = new Lantern({
token: async () => (await fetch("/telemetry-token").then((r) => r.json())).token,
});The token is a plain HS256 JWT with the key id in kid, so any language with an
HMAC can mint one. mintToken just saves you reaching for a JWT library. Its
grant lives in a claim named forest — the device wire's spelling, unchanged so
that tokens minted by @xeonr/forest and by this package are interchangeable.
Options
| Option | Default | |
|---|---|---|
| url | https://in.lntrn.dev | Lantern's client ingest. Batches go to ${url}/v1/logs and ${url}/v1/metrics. |
| token | — | A token, or a function returning one. Required. |
| attrs | — | Merged into every record; per-record attrs win. |
| logger | — | Sent as the logger (the OTLP scope name) on every log line. |
| release | — | Your app's release; sent as service.version (the resource's) on every log and event. Metrics never carried it: the ingest discarded it. |
| batchSize | 100 | Flush once this many records are queued. |
| flushInterval | 5000 | Flush at least this often (ms). 0 disables. |
| maxQueue | 10000 | Queue cap; past it the oldest are dropped. |
| retries | 3 | Attempts per request. |
| onError | — | Delivery failures and dropped records. |
| onResponse | — | The server's reply for each batch, including dropped field names. |
| fetch | globalThis.fetch | Override for tests or unusual runtimes. |
Custom fields
Attributes the project does not accept are dropped server-side and named in the
response — sending one is never an error, so shipping a new field before the
project knows about it will not break your fleet. Values are strings, numbers
and booleans; a value of any other type (null, NaN, an array, an object)
has no OTLP form, so it is dropped before sending and named the same way. To
see what is being dropped:
new Lantern({
token,
onResponse: (r) => {
if (r.droppedFields) console.warn("lantern dropped:", r.droppedFieldNames);
},
});Errors
lantern.error(err);
lantern.error(err, {
release: "1.4.2", // service.version (defaults to the client's `release`)
route: "/player", // url.path — the route or screen
sessionId: playbackId, // session.id — stitches the record to a session
attrs: { engine: "hls" },
});
lantern.error("upload failed", { code: 500 }); // the attrs form still worksAn Error becomes a log record at level error whose attrs carry
exception.type (the error's name, or its class when a subclass never set
one), exception.message and exception.stacktrace; the options become
service.version, url.path and session.id. That is the shape Lantern's
Issues screen groups on, so device and native crashes land next to browser and
server errors. The ingest treats all of those keys as built-in, so they need no
declaration.
The stack also goes in the log body, the way console.error(err) prints it, so
a view that shows only the body still has it.
The second argument is read as options only when every key in it is
release, route, sessionId or attrs; anything else is plain attrs, as
before options existed. So { route: "/a", code: 1 } is attrs, while a lone
{ route: "/a" } is the route option.
There is no session state in the client: pass sessionId per error, and put
"session.id" in the attrs of anything else that belongs to the session.
Endpoint
url defaults to https://in.lntrn.dev, Lantern's client ingest tier. The
name is deliberately not a telemetry. host: those are on browser block lists
and home DNS filters (Pi-hole, NextDNS), which is exactly where devices run.
new Lantern({ token, release }); // → https://in.lntrn.dev/v1/logs, /v1/metricsWire format
Each batch is OTLP/HTTP JSON, with the device token as the bearer:
- logs and events go to
POST /v1/logsas oneExportLogsServiceRequest. A log's level is its severity (severityNumberat the base of the band — trace 1, debug 5, info 9, warn 13, error 17, fatal 21 — and the band asseverityText), its message the string body, itsloggerthe scope name. An event is a record atinfowhose body is its name, withevent.name(andevent.value) attributes. Records are grouped by theirservice.version(therelease), which is sent on the resource, and by logger. - metrics go to
POST /v1/metricsas oneExportMetricsServiceRequest: a gauge point each, or a monotonic delta sum forkind: "counter". - attribute values are
stringValue,boolValue,intValue(an integer below 1e15 in magnitude) ordoubleValue.
That is exactly what the ingest used to build from the retired device format on the server, so records land as they always did. A batch with only logs, or only metrics, is a single request.
Catching crashes
// uncaught errors + unhandled rejections, with where they happened
const stop = lantern.captureErrors(() => ({ route: location.pathname, sessionId }));Every crash goes out as an exception (exception.type/message/stacktrace), so
Lantern's Issues groups it, including a throw of something that is not an
Error. The context is read at each crash, the same as error()'s options.
Opt-in on purpose: installing global handlers from a constructor is the kind of side effect that is miserable to debug when you did not know it happened. Call the returned function to remove them.
Shutting down
await lantern.flush(); // send what is queued
await lantern.close(); // flush and stop the background timerIn browsers the client also flushes on pagehide and when the tab is hidden,
as keepalive fetches (one for logs, one for metrics, started together) so
the batch survives the page going away. Each carries the token in the query
string, a text/plain body (which the ingest reads as OTLP JSON) and no
credentials, so it needs no preflight and passes the ingest's wildcard CORS
policy from any origin; sendBeacon (which always sends credentials, and is
therefore refused cross-origin) is only the fallback where fetch is missing.
In Node the background timer is unref'd, so it never keeps a process alive.
Reading
This package only writes. The live tail that @xeonr/forest/live used to
provide is gone; reads — queries and live tails — go through
@xeonr/telemetry-web/read.
Behaviour worth knowing
- Retries are exponential with jitter, and honour
Retry-After(a 429, or a 503 from the ingest). A 4xx that is not 429 is not retried — a bad token does not fix itself. - The queue is capped. A long offline stretch drops the oldest records rather than growing until the tab or process dies.
- Requests are all-or-nothing; a batch is up to two requests. Logs (with
events) and metrics are sent separately and retried separately, so a
rejected metrics request does not cost the logs, and vice versa.
onErrorhears about each failure;onResponsegets one reply per batch, covering what was accepted.
