Skip to content

πŸ“ˆ Open source, privacy-first web analytics β€” a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Add Nest.js & Fastify integrations

Blue Mouse9857c9068d23
diff --git a/docs/docs/integration-guides.md b/docs/docs/integration-guides.md
index dbc816d8b..fa724a423 100644
--- a/docs/docs/integration-guides.md
+++ b/docs/docs/integration-guides.md
@@ -58,8 +58,10 @@ Swetrix integrates with a wide range of platforms, frameworks, and tools. Choose
- [Django](/django-integration) (Python)
- [Express.js](/express-integration) (Node.js)
+- [Fastify](/fastify-integration) (Node.js)
- [Flask](/flask-integration) (Python)
- [Laravel](/laravel-integration) (PHP)
+- [NestJS](/nestjs-integration) (Node.js)
- [Ruby on Rails](/ruby-on-rails-integration)
## Google
diff --git a/docs/docs/integrations/fastify.md b/docs/docs/integrations/fastify.md
new file mode 100644
index 000000000..948f32f46
--- /dev/null
+++ b/docs/docs/integrations/fastify.md
@@ -0,0 +1,448 @@
+---
+title: Fastify
+slug: /fastify-integration
+---
+
+Integrate Swetrix with your [Fastify](https://fastify.dev/) application using the [`@swetrix/node`](https://github.com/swetrix/swetrix-node) server-side SDK to track page views, monitor errors, and capture custom events β€” all while staying privacy-friendly and GDPR-compliant.
+
+Unlike client-side integrations that inject a tracking script into the browser, `@swetrix/node` sends analytics data directly from your server. This means tracking works even when visitors have JavaScript disabled or use ad blockers, and no third-party scripts are loaded in the browser.
+
+## Installation
+
+```bash
+npm install @swetrix/node
+```
+
+## Setup
+
+Initialise the Swetrix client with your Project ID:
+
+```javascript
+import Fastify from 'fastify'
+import { Swetrix } from '@swetrix/node'
+
+const fastify = Fastify({ logger: true })
+const swetrix = new Swetrix('YOUR_PROJECT_ID')
+```
+
+:::caution
+Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.
+:::
+
+The `Swetrix` constructor accepts an optional second argument β€” an options object:
+
+```javascript
+const swetrix = new Swetrix('YOUR_PROJECT_ID', {
+ devMode: false,
+ disabled: process.env.NODE_ENV !== 'production',
+ apiURL: undefined, // only needed for self-hosted Swetrix
+})
+```
+
+| Option | Type | Description |
+| --- | --- | --- |
+| `devMode` | `boolean` | When `true`, all tracking logs are printed to the console |
+| `disabled` | `boolean` | When `true`, no data is sent to the server β€” useful for development |
+| `apiURL` | `string` | Custom API server URL (for self-hosted Swetrix) |
+| `unique` | `boolean` | When `true`, only unique events are saved |
+| `profileId` | `string` | Optional profile ID for long-term user tracking |
+
+## Tracking pageviews
+
+To track pageviews you need to pass the visitor's **IP address** and **User-Agent** header. Without these, unique visitor counting and live visitor tracking won't work. See the [Events API docs](/events-api#unique-visitors-tracking) for details.
+
+### Basic example
+
+```javascript
+fastify.get('/', async (request, reply) => {
+ const ip = request.ip
+ const userAgent = request.headers['user-agent']
+
+ await swetrix.trackPageView(ip, userAgent, {
+ pg: '/',
+ lc: request.headers['accept-language']?.split(',')[0],
+ ref: request.headers['referer'],
+ })
+
+ return { message: 'Hello World' }
+})
+```
+
+### Hook approach (recommended)
+
+Fastify's lifecycle hooks let you track pageviews automatically on every request without repeating code in each route handler. The `onRequest` hook runs before the route handler:
+
+```javascript
+fastify.addHook('onRequest', async (request, reply) => {
+ const ip = request.ip
+ const userAgent = request.headers['user-agent']
+
+ // Fire-and-forget β€” don't block the response
+ swetrix.trackPageView(ip, userAgent, {
+ pg: request.url,
+ lc: request.headers['accept-language']?.split(',')[0],
+ ref: request.headers['referer'],
+ })
+})
+```
+
+:::tip
+By not awaiting `trackPageView`, analytics calls happen in the background without adding latency to your responses. This is the recommended pattern for production.
+:::
+
+If your Fastify app runs behind a reverse proxy (e.g. Nginx, Cloudflare, or a load balancer), set the [`trustProxy`](https://fastify.dev/docs/latest/Reference/Server/#trustproxy) option so `request.ip` returns the real client IP:
+
+```javascript
+const fastify = Fastify({
+ trustProxy: true,
+})
+```
+
+### Plugin approach
+
+For a more Fastify-idiomatic solution, you can wrap the tracking logic in a plugin:
+
+```javascript
+import fp from 'fastify-plugin'
+import { Swetrix } from '@swetrix/node'
+
+export default fp(async function swetrixPlugin(fastify, opts) {
+ const swetrix = new Swetrix(opts.projectId, {
+ disabled: opts.disabled,
+ devMode: opts.devMode,
+ })
+
+ fastify.decorate('swetrix', swetrix)
+
+ fastify.addHook('onRequest', async (request) => {
+ swetrix.trackPageView(request.ip, request.headers['user-agent'], {
+ pg: request.url,
+ lc: request.headers['accept-language']?.split(',')[0],
+ ref: request.headers['referer'],
+ })
+ })
+})
+```
+
+Register the plugin in your app:
+
+```javascript
+import swetrixPlugin from './plugins/swetrix.js'
+
+fastify.register(swetrixPlugin, {
+ projectId: process.env.SWETRIX_PROJECT_ID,
+ disabled: process.env.NODE_ENV !== 'production',
+})
+```
+
+After registering, you can access the Swetrix instance from any route via `fastify.swetrix` or `request.server.swetrix`.
+
+### Pageview options
+
+The third argument to `trackPageView` is an options object:
+
+| Option | Type | Description |
+| --- | --- | --- |
+| `pg` | `string` | Page path (e.g. `/home`) |
+| `lc` | `string` | Visitor locale (e.g. `en-US`) |
+| `ref` | `string` | Referrer URL |
+| `so` | `string` | Traffic source (e.g. `utm_source`) |
+| `me` | `string` | Traffic medium (e.g. `utm_medium`) |
+| `ca` | `string` | Campaign (e.g. `utm_campaign`) |
+| `unique` | `boolean` | Only save unique visits |
+| `meta` | `object` | Custom metadata key-value pairs |
+
+## Tracking custom events
+
+Track specific actions β€” API calls, form submissions, purchases, etc.:
+
+```javascript
+fastify.post('/api/subscribe', async (request, reply) => {
+ swetrix.track(request.ip, request.headers['user-agent'], {
+ ev: 'NEWSLETTER_SUBSCRIBE',
+ page: '/subscribe',
+ meta: {
+ plan: request.body.plan,
+ },
+ })
+
+ return { success: true }
+})
+```
+
+### Event naming rules
+
+Event names must:
+
+- Contain only English letters (a-Z), numbers (0-9), underscores (`_`), and dots (`.`)
+- Be fewer than 64 characters
+- Start with an English letter
+
+We recommend `UPPER_SNAKE_CASE` for consistency (e.g. `NEWSLETTER_SUBSCRIBE`, `CHECKOUT_COMPLETED`).
+
+## Error tracking
+
+Use Fastify's `setErrorHandler` to report errors to Swetrix automatically:
+
+```javascript
+fastify.setErrorHandler((error, request, reply) => {
+ swetrix.trackError(request.ip, request.headers['user-agent'], {
+ name: error.name || 'Error',
+ message: error.message,
+ stackTrace: error.stack,
+ pg: request.url,
+ })
+
+ reply.status(error.statusCode || 500).send({
+ error: 'Internal Server Error',
+ })
+})
+```
+
+You can also track errors from specific routes:
+
+```javascript
+fastify.get('/api/data', async (request, reply) => {
+ try {
+ const data = await fetchExternalData()
+ return data
+ } catch (err) {
+ swetrix.trackError(request.ip, request.headers['user-agent'], {
+ name: err.name,
+ message: err.message,
+ stackTrace: err.stack,
+ pg: request.url,
+ })
+
+ reply.status(500).send({ error: 'Failed to fetch data' })
+ }
+})
+```
+
+## Heartbeat events
+
+Heartbeat events let Swetrix know a visitor's session is still active, powering the **Live Visitors** counter in your dashboard. They're most useful in long-lived connections like WebSocket sessions:
+
+```javascript
+import websocket from '@fastify/websocket'
+
+fastify.register(websocket)
+
+const HEARTBEAT_INTERVAL = 30_000
+
+fastify.get('/ws', { websocket: true }, (socket, request) => {
+ const ip = request.ip
+ const userAgent = request.headers['user-agent']
+
+ const interval = setInterval(() => {
+ swetrix.heartbeat(ip, userAgent)
+ }, HEARTBEAT_INTERVAL)
+
+ socket.on('close', () => clearInterval(interval))
+})
+```
+
+## Feature flags
+
+Evaluate feature flags server-side based on visitor context:
+
+```javascript
+fastify.get('/dashboard', async (request, reply) => {
+ const showNewDashboard = await swetrix.getFeatureFlag(
+ 'new-dashboard',
+ request.ip,
+ request.headers['user-agent'],
+ { profileId: request.user?.id },
+ false, // default value
+ )
+
+ if (showNewDashboard) {
+ return reply.view('dashboard-v2')
+ }
+
+ return reply.view('dashboard')
+})
+```
+
+You can also fetch all flags at once:
+
+```javascript
+const flags = await swetrix.getFeatureFlags(request.ip, request.headers['user-agent'])
+
+if (flags['beta-feature']) {
+ // Enable beta feature
+}
+```
+
+Feature flags are cached for 5 minutes. To force a refresh:
+
+```javascript
+swetrix.clearFeatureFlagsCache()
+```
+
+## A/B testing (experiments)
+
+Run server-side A/B tests and get the assigned variant for each visitor:
+
+```javascript
+fastify.get('/pricing', async (request, reply) => {
+ const variant = await swetrix.getExperiment(
+ 'pricing-experiment-id',
+ request.ip,
+ request.headers['user-agent'],
+ { profileId: request.user?.id },
+ null, // default variant
+ )
+
+ return {
+ showAnnualFirst: variant === 'annual-first',
+ }
+})
+```
+
+## Revenue attribution
+
+Use profile and session IDs to connect analytics with your payment provider (e.g. Paddle, Stripe):
+
+```javascript
+fastify.get('/checkout', async (request, reply) => {
+ const [profileId, sessionId] = await Promise.all([
+ swetrix.getProfileId(request.ip, request.headers['user-agent']),
+ swetrix.getSessionId(request.ip, request.headers['user-agent']),
+ ])
+
+ return {
+ checkoutConfig: {
+ customData: {
+ swetrix_profile_id: profileId,
+ swetrix_session_id: sessionId,
+ },
+ },
+ }
+})
+```
+
+## Disable tracking in development
+
+Use the `disabled` option to prevent tracking during development:
+
+```javascript
+const swetrix = new Swetrix('YOUR_PROJECT_ID', {
+ disabled: process.env.NODE_ENV !== 'production',
+})
+```
+
+Or use `devMode` to log tracking calls to the console without disabling them:
+
+```javascript
+const swetrix = new Swetrix('YOUR_PROJECT_ID', {
+ devMode: process.env.NODE_ENV === 'development',
+})
+```
+
+## Using environment variables for your Project ID
+
+Rather than hardcoding the Project ID, store it in an environment variable:
+
+```bash
+SWETRIX_PROJECT_ID=YOUR_PROJECT_ID
+```
+
+```javascript
+const swetrix = new Swetrix(process.env.SWETRIX_PROJECT_ID)
+```
+
+With Fastify's [`@fastify/env`](https://github.com/fastify/fastify-env) plugin:
+
+```javascript
+import fastifyEnv from '@fastify/env'
+
+const schema = {
+ type: 'object',
+ required: ['SWETRIX_PROJECT_ID'],
+ properties: {
+ SWETRIX_PROJECT_ID: { type: 'string' },
+ },
+}
+
+fastify.register(fastifyEnv, { schema, dotenv: true })
+```
+
+## Complete example
+
+Here's a full Fastify application with Swetrix analytics:
+
+```javascript
+import Fastify from 'fastify'
+import { Swetrix } from '@swetrix/node'
+
+const fastify = Fastify({
+ logger: true,
+ trustProxy: true,
+})
+
+const swetrix = new Swetrix(process.env.SWETRIX_PROJECT_ID, {
+ disabled: process.env.NODE_ENV !== 'production',
+})
+
+// Track pageviews on all requests
+fastify.addHook('onRequest', async (request) => {
+ swetrix.trackPageView(request.ip, request.headers['user-agent'], {
+ pg: request.url,
+ lc: request.headers['accept-language']?.split(',')[0],
+ ref: request.headers['referer'],
+ })
+})
+
+fastify.get('/', async () => {
+ return { message: 'Hello World' }
+})
+
+fastify.post('/api/contact', async (request) => {
+ swetrix.track(request.ip, request.headers['user-agent'], {
+ ev: 'CONTACT_FORM_SUBMITTED',
+ page: '/contact',
+ })
+
+ return { success: true }
+})
+
+// Error tracking
+fastify.setErrorHandler((error, request, reply) => {
+ swetrix.trackError(request.ip, request.headers['user-agent'], {
+ name: error.name || 'Error',
+ message: error.message,
+ stackTrace: error.stack,
+ pg: request.url,
+ })
+
+ reply.status(500).send({ error: 'Internal Server Error' })
+})
+
+fastify.listen({ port: 3000 }, (err) => {
+ if (err) {
+ fastify.log.error(err)
+ process.exit(1)
+ }
+})
+```
+
+## Check your installation
+
+Deploy your application (or temporarily enable `devMode`) and make a few requests. Within a minute you should see new pageviews appearing in your Swetrix dashboard.
+
+## Self-hosted Swetrix
+
+If you're self-hosting the [Swetrix API](https://github.com/Swetrix/swetrix-api), point the `apiURL` option to your instance:
+
+```javascript
+const swetrix = new Swetrix('YOUR_PROJECT_ID', {
+ apiURL: 'https://your-swetrix-instance.com/log',
+})
+```
+
+## Further reading
+
+- [`@swetrix/node` source code](https://github.com/swetrix/swetrix-node) β€” full source and documentation for the server-side SDK.
+- [Events API](/events-api) β€” API documentation for direct event submission.
+- [Fastify documentation](https://fastify.dev/docs/latest/) β€” official Fastify docs.
diff --git a/docs/docs/integrations/nestjs.md b/docs/docs/integrations/nestjs.md
new file mode 100644
index 000000000..cfe331e7c
--- /dev/null
+++ b/docs/docs/integrations/nestjs.md
@@ -0,0 +1,469 @@
+---
+title: NestJS
+slug: /nestjs-integration
+---
+
+Integrate Swetrix with your [NestJS](https://nestjs.com/) application using the [`@swetrix/node`](https://github.com/swetrix/swetrix-node) server-side SDK to track page views, monitor errors, and capture custom events β€” all while staying privacy-friendly and GDPR-compliant.
+
+Unlike client-side integrations that inject a tracking script into the browser, `@swetrix/node` sends analytics data directly from your server. This means tracking works even when visitors have JavaScript disabled or use ad blockers, and no third-party scripts are loaded in the browser.
+
+## Installation
+
+```bash
+npm install @swetrix/node
+```
+
+## Setup
+
+Create a dedicated module and service to keep your analytics logic organised and injectable across your application.
+
+### 1. Create the Swetrix service
+
+```typescript
+// src/swetrix/swetrix.service.ts
+import { Injectable } from '@nestjs/common'
+import { Swetrix } from '@swetrix/node'
+import { ConfigService } from '@nestjs/config'
+
+@Injectable()
+export class SwetrixService {
+ private readonly swetrix: Swetrix
+
+ constructor(private readonly configService: ConfigService) {
+ this.swetrix = new Swetrix(
+ this.configService.get<string>('SWETRIX_PROJECT_ID'),
+ {
+ disabled: this.configService.get('NODE_ENV') !== 'production',
+ },
+ )
+ }
+
+ trackPageView(ip: string, userAgent: string, options?: Record<string, any>) {
+ return this.swetrix.trackPageView(ip, userAgent, options)
+ }
+
+ track(ip: string, userAgent: string, options: Record<string, any>) {
+ return this.swetrix.track(ip, userAgent, options)
+ }
+
+ trackError(ip: string, userAgent: string, options: Record<string, any>) {
+ return this.swetrix.trackError(ip, userAgent, options)
+ }
+
+ heartbeat(ip: string, userAgent: string) {
+ return this.swetrix.heartbeat(ip, userAgent)
+ }
+
+ getFeatureFlag(
+ name: string,
+ ip: string,
+ userAgent: string,
+ options?: Record<string, any>,
+ defaultValue?: boolean,
+ ) {
+ return this.swetrix.getFeatureFlag(name, ip, userAgent, options, defaultValue)
+ }
+
+ getFeatureFlags(ip: string, userAgent: string, options?: Record<string, any>) {
+ return this.swetrix.getFeatureFlags(ip, userAgent, options)
+ }
+
+ getExperiment(
+ experimentId: string,
+ ip: string,
+ userAgent: string,
+ options?: Record<string, any>,
+ defaultVariant?: string | null,
+ ) {
+ return this.swetrix.getExperiment(experimentId, ip, userAgent, options, defaultVariant)
+ }
+
+ getProfileId(ip: string, userAgent: string) {
+ return this.swetrix.getProfileId(ip, userAgent)
+ }
+
+ getSessionId(ip: string, userAgent: string) {
+ return this.swetrix.getSessionId(ip, userAgent)
+ }
+
+ clearFeatureFlagsCache() {
+ this.swetrix.clearFeatureFlagsCache()
+ }
+
+ clearExperimentsCache() {
+ this.swetrix.clearExperimentsCache()
+ }
+}
+```
+
+### 2. Create the Swetrix module
+
+```typescript
+// src/swetrix/swetrix.module.ts
+import { Global, Module } from '@nestjs/common'
+import { SwetrixService } from './swetrix.service'
+
+@Global()
+@Module({
+ providers: [SwetrixService],
+ exports: [SwetrixService],
+})
+export class SwetrixModule {}
+```
+
+The `@Global()` decorator makes the module available everywhere without needing to import it in every feature module.
+
+### 3. Register in your app module
+
+```typescript
+// src/app.module.ts
+import { Module } from '@nestjs/common'
+import { ConfigModule } from '@nestjs/config'
+import { SwetrixModule } from './swetrix/swetrix.module'
+
+@Module({
+ imports: [
+ ConfigModule.forRoot({ isGlobal: true }),
+ SwetrixModule,
+ ],
+})
+export class AppModule {}
+```
+
+:::caution
+Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), or set the `SWETRIX_PROJECT_ID` environment variable.
+:::
+
+## Tracking pageviews
+
+To track pageviews you need to pass the visitor's **IP address** and **User-Agent** header. Without these, unique visitor counting and live visitor tracking won't work. See the [Events API docs](/events-api#unique-visitors-tracking) for details.
+
+### Interceptor approach (recommended)
+
+An interceptor lets you track pageviews automatically on every request without repeating code in each controller:
+
+```typescript
+// src/swetrix/swetrix.interceptor.ts
+import {
+ Injectable,
+ NestInterceptor,
+ ExecutionContext,
+ CallHandler,
+} from '@nestjs/common'
+import { Observable } from 'rxjs'
+import { SwetrixService } from './swetrix.service'
+
+@Injectable()
+export class SwetrixInterceptor implements NestInterceptor {
+ constructor(private readonly swetrix: SwetrixService) {}
+
+ intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
+ const req = context.switchToHttp().getRequest()
+
+ // Fire-and-forget β€” don't block the response
+ this.swetrix.trackPageView(req.ip, req.headers['user-agent'], {
+ pg: req.path,
+ lc: req.headers['accept-language']?.split(',')[0],
+ ref: req.headers['referer'],
+ })
+
+ return next.handle()
+ }
+}
+```
+
+Register it globally in your `main.ts`:
+
+```typescript
+// src/main.ts
+import { NestFactory } from '@nestjs/core'
+import { AppModule } from './app.module'
+import { SwetrixInterceptor } from './swetrix/swetrix.interceptor'
+import { SwetrixService } from './swetrix/swetrix.service'
+
+async function bootstrap() {
+ const app = await NestFactory.create(AppModule)
+
+ const swetrixService = app.get(SwetrixService)
+ app.useGlobalInterceptors(new SwetrixInterceptor(swetrixService))
+
+ await app.listen(3000)
+}
+bootstrap()
+```
+
+:::tip
+By not awaiting `trackPageView`, analytics calls happen in the background without adding latency to your responses. This is the recommended pattern for production.
+:::
+
+If your NestJS app runs behind a reverse proxy (e.g. Nginx, Cloudflare, or a load balancer), enable the Express `trust proxy` setting in `main.ts` so `req.ip` returns the real client IP:
+
+```typescript
+const app = await NestFactory.create(AppModule)
+app.getHttpAdapter().getInstance().set('trust proxy', true)
+```
+
+### Per-route tracking
+
+You can also track pageviews in individual controllers by injecting the service:
+
+```typescript
+import { Controller, Get, Req } from '@nestjs/common'
+import { Request } from 'express'
+import { SwetrixService } from '../swetrix/swetrix.service'
+
+@Controller()
+export class AppController {
+ constructor(private readonly swetrix: SwetrixService) {}
+
+ @Get()
+ getHome(@Req() req: Request) {
+ this.swetrix.trackPageView(req.ip, req.headers['user-agent'], {
+ pg: '/',
+ })
+
+ return { message: 'Hello World' }
+ }
+}
+```
+
+### Pageview options
+
+The third argument to `trackPageView` is an options object:
+
+| Option | Type | Description |
+| --- | --- | --- |
+| `pg` | `string` | Page path (e.g. `/home`) |
+| `lc` | `string` | Visitor locale (e.g. `en-US`) |
+| `ref` | `string` | Referrer URL |
+| `so` | `string` | Traffic source (e.g. `utm_source`) |
+| `me` | `string` | Traffic medium (e.g. `utm_medium`) |
+| `ca` | `string` | Campaign (e.g. `utm_campaign`) |
+| `unique` | `boolean` | Only save unique visits |
+| `meta` | `object` | Custom metadata key-value pairs |
+
+## Tracking custom events
+
+Track specific actions β€” API calls, form submissions, purchases, etc.:
+
+```typescript
+import { Controller, Post, Req, Body } from '@nestjs/common'
+import { Request } from 'express'
+import { SwetrixService } from '../swetrix/swetrix.service'
+
+@Controller('api')
+export class SubscriptionController {
+ constructor(private readonly swetrix: SwetrixService) {}
+
+ @Post('subscribe')
+ subscribe(@Req() req: Request, @Body() body: { plan: string }) {
+ this.swetrix.track(req.ip, req.headers['user-agent'], {
+ ev: 'NEWSLETTER_SUBSCRIBE',
+ page: '/subscribe',
+ meta: { plan: body.plan },
+ })
+
+ return { success: true }
+ }
+}
+```
+
+### Event naming rules
+
+Event names must:
+
+- Contain only English letters (a-Z), numbers (0-9), underscores (`_`), and dots (`.`)
+- Be fewer than 64 characters
+- Start with an English letter
+
+We recommend `UPPER_SNAKE_CASE` for consistency (e.g. `NEWSLETTER_SUBSCRIBE`, `CHECKOUT_COMPLETED`).
+
+## Error tracking
+
+Use a NestJS exception filter to report errors to Swetrix automatically:
+
+```typescript
+// src/swetrix/swetrix-exception.filter.ts
+import {
+ Catch,
+ ArgumentsHost,
+ HttpException,
+ HttpStatus,
+} from '@nestjs/common'
+import { BaseExceptionFilter } from '@nestjs/core'
+import { SwetrixService } from './swetrix.service'
+
+@Catch()
+export class SwetrixExceptionFilter extends BaseExceptionFilter {
+ constructor(private readonly swetrix: SwetrixService) {
+ super()
+ }
+
+ catch(exception: unknown, host: ArgumentsHost) {
+ const ctx = host.switchToHttp()
+ const req = ctx.getRequest()
+
+ const error =
+ exception instanceof Error
+ ? exception
+ : new Error(String(exception))
+
+ this.swetrix.trackError(req.ip, req.headers['user-agent'], {
+ name: error.name || 'Error',
+ message: error.message,
+ stackTrace: error.stack,
+ pg: req.path,
+ })
+
+ super.catch(exception, host)
+ }
+}
+```
+
+Register the filter globally in `main.ts`:
+
+```typescript
+const swetrixService = app.get(SwetrixService)
+app.useGlobalFilters(new SwetrixExceptionFilter(swetrixService))
+```
+
+You can also track errors from specific services:
+
+```typescript
+try {
+ const data = await this.httpService.get('https://api.example.com/data')
+ return data
+} catch (err) {
+ this.swetrix.trackError(ip, userAgent, {
+ name: err.name,
+ message: err.message,
+ stackTrace: err.stack,
+ pg: '/api/data',
+ })
+
+ throw new InternalServerErrorException('Failed to fetch data')
+}
+```
+
+## Feature flags
+
+Evaluate feature flags server-side based on visitor context:
+
+```typescript
+@Get('dashboard')
+async getDashboard(@Req() req: Request) {
+ const showNewDashboard = await this.swetrix.getFeatureFlag(
+ 'new-dashboard',
+ req.ip,
+ req.headers['user-agent'],
+ { profileId: req['user']?.id },
+ false,
+ )
+
+ return { template: showNewDashboard ? 'dashboard-v2' : 'dashboard' }
+}
+```
+
+You can also fetch all flags at once:
+
+```typescript
+const flags = await this.swetrix.getFeatureFlags(ip, userAgent)
+
+if (flags['beta-feature']) {
+ // Enable beta feature
+}
+```
+
+Feature flags are cached for 5 minutes. To force a refresh:
+
+```typescript
+this.swetrix.clearFeatureFlagsCache()
+```
+
+## A/B testing (experiments)
+
+Run server-side A/B tests and get the assigned variant for each visitor:
+
+```typescript
+@Get('pricing')
+async getPricing(@Req() req: Request) {
+ const variant = await this.swetrix.getExperiment(
+ 'pricing-experiment-id',
+ req.ip,
+ req.headers['user-agent'],
+ { profileId: req['user']?.id },
+ null,
+ )
+
+ return {
+ showAnnualFirst: variant === 'annual-first',
+ }
+}
+```
+
+## Revenue attribution
+
+Use profile and session IDs to connect analytics with your payment provider (e.g. Paddle, Stripe):
+
+```typescript
+@Get('checkout')
+async getCheckout(@Req() req: Request) {
+ const [profileId, sessionId] = await Promise.all([
+ this.swetrix.getProfileId(req.ip, req.headers['user-agent']),
+ this.swetrix.getSessionId(req.ip, req.headers['user-agent']),
+ ])
+
+ return {
+ checkoutConfig: {
+ customData: {
+ swetrix_profile_id: profileId,
+ swetrix_session_id: sessionId,
+ },
+ },
+ }
+}
+```
+
+## Disable tracking in development
+
+The service example above already disables tracking when `NODE_ENV` isn't `production`. You can also use `devMode` to log calls to the console during development:
+
+```typescript
+this.swetrix = new Swetrix(
+ this.configService.get<string>('SWETRIX_PROJECT_ID'),
+ {
+ devMode: this.configService.get('NODE_ENV') === 'development',
+ },
+)
+```
+
+## Using environment variables for your Project ID
+
+Add the `SWETRIX_PROJECT_ID` variable to your `.env` file:
+
+```
+SWETRIX_PROJECT_ID=YOUR_PROJECT_ID
+```
+
+The `SwetrixService` shown above already reads from `ConfigService`, which loads environment variables automatically when using `ConfigModule.forRoot()`.
+
+## Check your installation
+
+Deploy your application (or temporarily enable `devMode`) and make a few requests. Within a minute you should see new pageviews appearing in your Swetrix dashboard.
+
+## Self-hosted Swetrix
+
+If you're self-hosting the [Swetrix API](https://github.com/Swetrix/swetrix-api), point the `apiURL` option to your instance:
+
+```typescript
+this.swetrix = new Swetrix('YOUR_PROJECT_ID', {
+ apiURL: 'https://your-swetrix-instance.com/log',
+})
+```
+
+## Further reading
+
+- [`@swetrix/node` source code](https://github.com/swetrix/swetrix-node) β€” full source and documentation for the server-side SDK.
+- [Express.js integration](/express-integration) β€” if you use NestJS with Express under the hood, the Express guide covers lower-level patterns.
+- [Events API](/events-api) β€” API documentation for direct event submission.
+- [NestJS documentation](https://docs.nestjs.com/) β€” official NestJS docs.
diff --git a/docs/sidebars.js b/docs/sidebars.js
index 751e4c0b7..7c14d7f43 100644
--- a/docs/sidebars.js
+++ b/docs/sidebars.js
@@ -19,6 +19,7 @@ module.exports = {
'integrations/drupal',
'integrations/eleventy',
'integrations/express',
+ 'integrations/fastify',
'integrations/framer',
'integrations/ghost',
'integrations/gitbook',
@@ -31,6 +32,7 @@ module.exports = {
'integrations/joomla',
'integrations/laravel',
'integrations/mkdocs',
+ 'integrations/nestjs',
'integrations/prestashop',
{
type: 'category',