Analog is the full-stack meta-framework for Angular, built on Vite and Nitro. An Analog app runs code in two places:
| Where | What to use |
|---|---|
| Browser | The @understand/understand-js SDK and an Angular ErrorHandler |
Server (server-side rendering, src/server API routes and middleware) |
A Nitro plugin and a small fetch helper |
The server part uses the HTTP API directly, so it works with every Nitro deployment preset, including edge platforms. For a plain Angular app without SSR, the Angular guide is all you need.
npm install @understand/understand-js
Create two input keys in your channel (Settings → Input Tokens), one for the browser and one for the server, and add them to .env:
# included in the browser bundle: that is fine, an input key can only send events
VITE_UNDERSTAND_TOKEN=browser-input-key
# server only, read at runtime
UNDERSTAND_TOKEN=server-input-key
Vite only exposes variables prefixed with VITE_ to browser code. On your hosting platform, set UNDERSTAND_TOKEN as a runtime environment variable of the server.
This helper sends an event with fetch. It is used by the Nitro plugin and, during server-side rendering, by the Angular error handler:
// src/server/utils/understand.ts
type Fields = Record<string, unknown>;
const ENDPOINT = 'https://api.understand.io/';
function serverToken(): string | undefined {
return (globalThis as any).process?.env?.['UNDERSTAND_TOKEN'];
}
// turns " at fn (file:line:col)" lines into stack frames
function parseStack(stack = '') {
return stack
.split('\n')
.slice(1)
.map(line => line.match(/at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?$/))
.filter((match): match is RegExpMatchArray => match !== null)
.map(([, fn, file, line, column]) => ({
function: fn || '<anonymous>',
file,
line: Number(line),
column: Number(column)
}));
}
async function send(event: Fields) {
const token = serverToken();
if (!token) {
return;
}
try {
await fetch(ENDPOINT + token, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ env: import.meta.env.PROD ? 'production' : 'development', timestamp: Date.now(), ...event }),
// never let error reporting hang a request
signal: AbortSignal.timeout(3000)
});
} catch {
// reporting must never break the app
}
}
export function reportToUnderstand(error: unknown, fields: Fields = {}) {
const err = error instanceof Error ? error : new Error(String(error));
const stack = parseStack(err.stack);
return send({
message: err.message,
level: 'error',
class: err.name,
file: stack[0]?.file,
line: stack[0]?.line,
stack,
tags: ['analog'],
...fields
});
}
export function logToUnderstand(message: string, level = 'info', fields: Fields = {}) {
return send({ message, level, tags: ['analog'], ...fields });
}
Initialise the SDK in the browser entry point, src/main.ts. It is not used by server-side rendering, which starts from src/main.server.ts:
// src/main.ts
import 'zone.js';
import { bootstrapApplication } from '@angular/platform-browser';
import Understand from '@understand/understand-js';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
if (import.meta.env['VITE_UNDERSTAND_TOKEN']) {
Understand.init({
env: import.meta.env.PROD ? 'production' : 'development',
token: import.meta.env['VITE_UNDERSTAND_TOKEN']
}).catchErrors();
}
bootstrapApplication(AppComponent, appConfig);
Angular sends errors from components, services and event handlers to its ErrorHandler, in the browser and while rendering on the server. This handler reports them with the SDK in the browser and with the server helper during SSR, then keeps Angular's console output:
// src/app/understand-error-handler.ts
import { ErrorHandler, Injectable, PLATFORM_ID, inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import Understand from '@understand/understand-js';
import { reportToUnderstand } from '../server/utils/understand';
@Injectable()
export class UnderstandErrorHandler extends ErrorHandler {
private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
override handleError(error: unknown) {
if (this.isBrowser) {
Understand.logError(error);
} else {
void reportToUnderstand(error, { source: 'angular-ssr' });
}
super.handleError(error);
}
}
Register it in app.config.ts. The server config is merged with this one, so it applies to SSR too:
// src/app/app.config.ts
import { ApplicationConfig, ErrorHandler } from '@angular/core';
import { UnderstandErrorHandler } from './understand-error-handler';
export const appConfig: ApplicationConfig = {
providers: [
// ...your existing providers (provideFileRouter(), provideHttpClient(), ...)
{ provide: ErrorHandler, useClass: UnderstandErrorHandler }
]
};
Errors thrown in API routes and server middleware that nothing catches are reported by a Nitro plugin. Analog uses src/server as Nitro's source folder, so plugins go in src/server/plugins:
// src/server/plugins/understand.ts
import type { NitroApp } from 'nitropack';
import { reportToUnderstand } from '../utils/understand';
export default (nitroApp: NitroApp) => {
nitroApp.hooks.hook('error', async (error, { event }) => {
const statusCode = (error as { statusCode?: number }).statusCode ?? 500;
// createError({ statusCode: 404 }) and other 4xx responses are expected
if (statusCode < 500) {
return;
}
await reportToUnderstand(error, {
status: statusCode,
method: event?.method,
path: event?.path
});
});
};
The plugin is a plain function, which is all a Nitro plugin is (defineNitroPlugin only adds types), so it needs no auto-imports.
For errors you handle yourself, call the helper:
// src/server/routes/api/v1/checkout.post.ts
import { createError, defineEventHandler, readBody } from 'h3';
import { logToUnderstand, reportToUnderstand } from '../../../utils/understand';
export default defineEventHandler(async event => {
try {
const order = await createOrder(await readBody(event));
await logToUnderstand('order created', 'info', { order_id: order.id });
return order;
} catch (error) {
await reportToUnderstand(error, { path: event.path, tags: ['analog', 'checkout'] });
throw createError({ statusCode: 500, statusMessage: 'Checkout failed' });
}
});
Pass per-request values such as user_id like this on each call; a server handles many requests at once, so don't keep them in module-level variables.