π 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!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
FastAPI / ASP.NET integration guides
Blue Mouse2c607ed5f631
diff --git a/docs/docs/integration-guides.md b/docs/docs/integration-guides.mdindex fa724a423..7bb098654 100644--- a/docs/docs/integration-guides.md+++ b/docs/docs/integration-guides.md@@ -56,8 +56,10 @@ Swetrix integrates with a wide range of platforms, frameworks, and tools. Choose## Backend frameworks+- [ASP.NET](/aspnet-integration) (C#)- [Django](/django-integration) (Python)- [Express.js](/express-integration) (Node.js)+- [FastAPI](/fastapi-integration) (Python)- [Fastify](/fastify-integration) (Node.js)- [Flask](/flask-integration) (Python)- [Laravel](/laravel-integration) (PHP)diff --git a/docs/docs/integrations/aspnet.md b/docs/docs/integrations/aspnet.mdnew file mode 100644index 000000000..76908378e--- /dev/null+++ b/docs/docs/integrations/aspnet.md@@ -0,0 +1,601 @@+---+title: ASP.NET+slug: /aspnet-integration+---++Integrate Swetrix with your [ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/) or [ASP.NET Framework](https://dotnet.microsoft.com/en-us/apps/aspnet) application to track page views, monitor errors, and capture custom events β all while staying privacy-friendly and GDPR-compliant.++This guide covers Razor Pages, MVC, and Blazor setups, as well as server-side tracking via the Events API for API-only applications.++## Client-side tracking++The recommended approach for apps that serve HTML (Razor Pages, MVC, Blazor Server with SSR) is to add the Swetrix tracking script to your shared layout.++### ASP.NET Core (Razor Pages / MVC)++#### 1. Add the tracking script to your layout++Open your shared layout file β typically `Views/Shared/_Layout.cshtml` (MVC) or `Pages/Shared/_Layout.cshtml` (Razor Pages) β and add the Swetrix script inside the `<head>` tag and the initialisation snippet before the closing `</body>` tag:++```html+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>@ViewData["Title"] - My App</title>++ <!-- Swetrix Analytics -->+ <script src="https://swetrix.org/swetrix.js" defer></script>+</head>+<body>+ @RenderBody()++ <!-- Swetrix Analytics -->+ <script>+ document.addEventListener('DOMContentLoaded', function () {+ swetrix.init('YOUR_PROJECT_ID')+ swetrix.trackViews()+ })+ </script>++ <noscript>+ <img+ src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"+ alt=""+ referrerpolicy="no-referrer-when-downgrade"+ />+ </noscript>++ @await RenderSectionAsync("Scripts", required: false)+</body>+</html>+```++:::caution+Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.+:::++#### 2. Disable tracking in development (recommended)++Wrap the snippets in an environment check so they only load in production:++```html+<environment include="Production">+ <script src="https://swetrix.org/swetrix.js" defer></script>+</environment>+```++And for the body initialisation:++```html+<environment include="Production">+ <script>+ document.addEventListener('DOMContentLoaded', function () {+ swetrix.init('YOUR_PROJECT_ID')+ swetrix.trackViews()+ })+ </script>++ <noscript>+ <img+ src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"+ alt=""+ referrerpolicy="no-referrer-when-downgrade"+ />+ </noscript>+</environment>+```++The `<environment>` tag helper is built into ASP.NET Core and reads from the `ASPNETCORE_ENVIRONMENT` variable.++:::tip+During development, Swetrix ignores `localhost` traffic by default. If you want to verify tracking locally without changing your environment, you can temporarily set `devMode: true`:++```js+swetrix.init('YOUR_PROJECT_ID', { devMode: true })+```++Remember to remove this before deploying.+:::++### ASP.NET Framework (MVC)++#### 1. Add the tracking script to your layout++Open `Views/Shared/_Layout.cshtml` and add the Swetrix script:++```html+<!DOCTYPE html>+<html>+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>@ViewBag.Title - My App</title>+ @Styles.Render("~/Content/css")++ <!-- Swetrix Analytics -->+ <script src="https://swetrix.org/swetrix.js" defer></script>+</head>+<body>+ @RenderBody()++ <!-- Swetrix Analytics -->+ <script>+ document.addEventListener('DOMContentLoaded', function () {+ swetrix.init('YOUR_PROJECT_ID')+ swetrix.trackViews()+ })+ </script>++ <noscript>+ <img+ src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"+ alt=""+ referrerpolicy="no-referrer-when-downgrade"+ />+ </noscript>++ @Scripts.Render("~/bundles/jquery")+ @RenderSection("scripts", required: false)+</body>+</html>+```++#### 2. Disable tracking in development++ASP.NET Framework doesn't have a built-in `<environment>` tag helper. Use a conditional check in Razor instead:++```html+@if (!HttpContext.Current.IsDebuggingEnabled)+{+ <script src="https://swetrix.org/swetrix.js" defer></script>+}+```++And for the body initialisation:++```html+@if (!HttpContext.Current.IsDebuggingEnabled)+{+ <script>+ document.addEventListener('DOMContentLoaded', function () {+ swetrix.init('YOUR_PROJECT_ID')+ swetrix.trackViews()+ })+ </script>++ <noscript>+ <img+ src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"+ alt=""+ referrerpolicy="no-referrer-when-downgrade"+ />+ </noscript>+}+```++This uses the `debug` attribute from your `web.config` `<compilation>` element.++## Store your Project ID in configuration (optional)++Rather than hardcoding the Project ID in your layout, you can manage it through configuration so it stays in one place.++### ASP.NET Core++**1. Add to `appsettings.json`:**++```json+{+ "Swetrix": {+ "ProjectId": "YOUR_PROJECT_ID"+ }+}+```++**2. Inject configuration into your layout using `@inject`:**++```html+@inject Microsoft.Extensions.Configuration.IConfiguration Configuration++<environment include="Production">+ <script src="https://swetrix.org/swetrix.js" defer></script>+ <script>+ document.addEventListener('DOMContentLoaded', function () {+ swetrix.init('@Configuration["Swetrix:ProjectId"]')+ swetrix.trackViews()+ })+ </script>++ <noscript>+ <img+ src="https://api.swetrix.com/log/noscript?pid=@Configuration["Swetrix:ProjectId"]"+ alt=""+ referrerpolicy="no-referrer-when-downgrade"+ />+ </noscript>+</environment>+```++You can also use an environment variable instead. ASP.NET Core's configuration system supports this out of the box:++```bash+export Swetrix__ProjectId=YOUR_PROJECT_ID+```++### ASP.NET Framework++**1. Add to `web.config`:**++```xml+<appSettings>+ <add key="Swetrix:ProjectId" value="YOUR_PROJECT_ID" />+</appSettings>+```++**2. Reference it in your layout:**++```html+<script>+ document.addEventListener('DOMContentLoaded', function () {+ swetrix.init('@System.Configuration.ConfigurationManager.AppSettings["Swetrix:ProjectId"]')+ swetrix.trackViews()+ })+</script>+```++## Check your installation++Deploy your application (or temporarily enable `devMode`) and visit a few pages. Within a minute you should see new pageviews appearing in your Swetrix dashboard.++## Error tracking++Enable automatic client-side error monitoring by adding `trackErrors()` to the initialisation snippet. This captures unhandled JavaScript errors and reports them to Swetrix.++```html+<script>+ document.addEventListener('DOMContentLoaded', function () {+ swetrix.init('YOUR_PROJECT_ID')+ swetrix.trackViews()+ swetrix.trackErrors()+ })+</script>+```++Errors will appear in the **Errors** tab of your project dashboard. See the [tracking script reference](/swetrix-js-reference#trackerrors) for options like `sampleRate` and `callback`.++## Tracking custom events++Custom events let you track specific user interactions β form submissions, button clicks, feature usage, and more. Since the Swetrix script is loaded globally, you can call `swetrix.track()` from any inline script or JavaScript file.++### Example: tracking form submissions++Track when users submit a contact form:++```html+<form id="contact-form" method="post" asp-action="Contact">+ <!-- form fields -->+ <button type="submit">Send message</button>+</form>++<script>+ document.getElementById('contact-form')?.addEventListener('submit', function () {+ if (typeof swetrix !== 'undefined') {+ swetrix.track({+ ev: 'CONTACT_FORM_SUBMITTED',+ meta: {+ page: window.location.pathname,+ },+ })+ }+ })+</script>+```++### Example: tracking outbound links++Track clicks on external links across your site. Add this to your layout file:++```html+<script>+ document.addEventListener('DOMContentLoaded', function () {+ document.querySelectorAll('a[href^="http"]').forEach(function (link) {+ if (link.hostname !== window.location.hostname) {+ link.addEventListener('click', function () {+ if (typeof swetrix !== 'undefined') {+ swetrix.track({+ ev: 'OUTBOUND_CLICK',+ meta: { url: link.href },+ })+ }+ })+ }+ })+ })+</script>+```++### 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. `CONTACT_FORM_SUBMITTED`, `OUTBOUND_CLICK`).++## Blazor++### Blazor Server / Blazor Web App (interactive server)++For Blazor apps that render on the server, add the Swetrix script to your host page. In .NET 8+ with Blazor Web App, this is `Components/App.razor`. In earlier versions, use `Pages/_Host.cshtml` or `Pages/_Layout.cshtml`:++```html+<head>+ <!-- other head content -->+ <script src="https://swetrix.org/swetrix.js" defer></script>+</head>+<body>+ <!-- Blazor root component -->++ <script>+ document.addEventListener('DOMContentLoaded', function () {+ swetrix.init('YOUR_PROJECT_ID')+ swetrix.trackViews()+ })+ </script>+</body>+```++Blazor Server uses SignalR for updates and doesn't trigger full page navigations. Swetrix's `trackViews()` listens for History API changes, so navigations that use `NavigationManager` will be tracked automatically.++### Blazor WebAssembly++For standalone Blazor WASM apps, add the script to `wwwroot/index.html`:++```html+<head>+ <script src="https://swetrix.org/swetrix.js" defer></script>+</head>+<body>+ <div id="app">Loading...</div>++ <script src="_framework/blazor.webassembly.js"></script>+ <script>+ document.addEventListener('DOMContentLoaded', function () {+ swetrix.init('YOUR_PROJECT_ID')+ swetrix.trackViews()+ })+ </script>+</body>+```++## Server-side tracking (API-only apps)++If your ASP.NET application is a pure API (no HTML views), you can track events server-side using the [Events API](/events-api) directly with `HttpClient`.++### Setup++Register a typed `HttpClient` for Swetrix in `Program.cs`:++```csharp+builder.Services.AddHttpClient("Swetrix", client =>+{+ client.BaseAddress = new Uri("https://api.swetrix.com");+ client.DefaultRequestHeaders.Add("Accept", "application/json");+});+```++### Create a tracking service++```csharp+public class SwetrixService+{+ private readonly HttpClient _httpClient;+ private readonly string _projectId;++ public SwetrixService(IHttpClientFactory httpClientFactory, IConfiguration configuration)+ {+ _httpClient = httpClientFactory.CreateClient("Swetrix");+ _projectId = configuration["Swetrix:ProjectId"]+ ?? throw new InvalidOperationException("Swetrix:ProjectId is not configured.");+ }++ public async Task TrackPageViewAsync(string ip, string userAgent, string page, string? locale = null, string? referrer = null)+ {+ var payload = new Dictionary<string, object?>+ {+ ["pid"] = _projectId,+ ["pg"] = page,+ ["lc"] = locale,+ ["ref"] = referrer,+ };++ var request = new HttpRequestMessage(HttpMethod.Post, "/log")+ {+ Content = JsonContent.Create(payload),+ };+ request.Headers.Add("User-Agent", userAgent);+ request.Headers.Add("X-Client-IP-Address", ip);++ await _httpClient.SendAsync(request);+ }++ public async Task TrackEventAsync(string ip, string userAgent, string eventName, string? page = null, Dictionary<string, object?>? meta = null)+ {+ var payload = new Dictionary<string, object?>+ {+ ["pid"] = _projectId,+ ["ev"] = eventName,+ ["pg"] = page,+ ["meta"] = meta,+ };++ var request = new HttpRequestMessage(HttpMethod.Post, "/log/custom")+ {+ Content = JsonContent.Create(payload),+ };+ request.Headers.Add("User-Agent", userAgent);+ request.Headers.Add("X-Client-IP-Address", ip);++ await _httpClient.SendAsync(request);+ }++ public async Task TrackErrorAsync(string ip, string userAgent, string name, string? message = null, string? stackTrace = null, string? page = null)+ {+ var payload = new Dictionary<string, object?>+ {+ ["pid"] = _projectId,+ ["name"] = name,+ ["message"] = message,+ ["stackTrace"] = stackTrace,+ ["pg"] = page,+ };++ var request = new HttpRequestMessage(HttpMethod.Post, "/log/error")+ {+ Content = JsonContent.Create(payload),+ };+ request.Headers.Add("User-Agent", userAgent);+ request.Headers.Add("X-Client-IP-Address", ip);++ await _httpClient.SendAsync(request);+ }+}+```++### Register the service++```csharp+builder.Services.AddSingleton<SwetrixService>();+```++### Middleware approach (recommended)++Track pageviews automatically on every request:++```csharp+public class SwetrixMiddleware+{+ private readonly RequestDelegate _next;+ private readonly SwetrixService _swetrix;++ public SwetrixMiddleware(RequestDelegate next, SwetrixService swetrix)+ {+ _next = next;+ _swetrix = swetrix;+ }++ public async Task InvokeAsync(HttpContext context)+ {+ var ip = context.Connection.RemoteIpAddress?.ToString() ?? "";+ var userAgent = context.Request.Headers.UserAgent.ToString();+ var page = context.Request.Path.ToString();+ var locale = context.Request.Headers.AcceptLanguage.ToString().Split(',').FirstOrDefault();+ var referrer = context.Request.Headers.Referer.ToString();++ // Fire-and-forget β don't block the response+ _ = _swetrix.TrackPageViewAsync(ip, userAgent, page, locale, referrer);++ await _next(context);+ }+}+```++Register the middleware in `Program.cs`:++```csharp+app.UseMiddleware<SwetrixMiddleware>();+```++:::tip+By using fire-and-forget (`_ = ...`), the analytics call runs in the background without adding latency to your responses. This is the recommended pattern for production.+:::++If your application runs behind a reverse proxy (e.g. Nginx, Cloudflare, or a load balancer), configure [forwarded headers](https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer) so `RemoteIpAddress` returns the real client IP:++```csharp+builder.Services.Configure<ForwardedHeadersOptions>(options =>+{+ options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;+});++// Add before other middleware+app.UseForwardedHeaders();+```++### Per-route tracking++Inject the service directly into controllers or minimal API handlers:++```csharp+app.MapPost("/api/subscribe", async (SwetrixService swetrix, HttpContext context) =>+{+ var ip = context.Connection.RemoteIpAddress?.ToString() ?? "";+ var userAgent = context.Request.Headers.UserAgent.ToString();++ _ = swetrix.TrackEventAsync(ip, userAgent, "NEWSLETTER_SUBSCRIBE", "/subscribe");++ return Results.Ok(new { success = true });+});+```++### Error tracking++Use exception-handling middleware to report errors:++```csharp+app.UseExceptionHandler(errorApp =>+{+ errorApp.Run(async context =>+ {+ var exception = context.Features.Get<IExceptionHandlerFeature>()?.Error;+ if (exception is not null)+ {+ var swetrix = context.RequestServices.GetRequiredService<SwetrixService>();+ var ip = context.Connection.RemoteIpAddress?.ToString() ?? "";+ var userAgent = context.Request.Headers.UserAgent.ToString();++ _ = swetrix.TrackErrorAsync(+ ip,+ userAgent,+ exception.GetType().Name,+ exception.Message,+ exception.StackTrace,+ context.Request.Path+ );+ }++ context.Response.StatusCode = 500;+ await context.Response.WriteAsJsonAsync(new { error = "Internal Server Error" });+ });+});+```++## Self-hosted Swetrix++If you're self-hosting the [Swetrix API](https://github.com/Swetrix/swetrix-api), point the script or API base URL to your instance.++**Client-side:**++```js+swetrix.init('YOUR_PROJECT_ID', {+ apiURL: 'https://your-swetrix-instance.com/log',+})+```++**Server-side:**++```csharp+builder.Services.AddHttpClient("Swetrix", client =>+{+ client.BaseAddress = new Uri("https://your-swetrix-instance.com");+});+```++## Further reading++- [Tracking script reference](/swetrix-js-reference) β full API documentation for `init()`, `track()`, `trackViews()`, `trackErrors()`, and more.+- [Events API](/events-api) β API documentation for direct event submission.+- [ASP.NET Core documentation](https://learn.microsoft.com/en-us/aspnet/core/) β official ASP.NET Core docs.diff --git a/docs/docs/integrations/fastapi.md b/docs/docs/integrations/fastapi.mdnew file mode 100644index 000000000..f66e14a00--- /dev/null+++ b/docs/docs/integrations/fastapi.md@@ -0,0 +1,666 @@+---+title: FastAPI+slug: /fastapi-integration+---++Integrate Swetrix with your [FastAPI](https://fastapi.tiangolo.com/) application 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, this approach sends analytics data directly from your server using the Swetrix [Events API](/events-api). 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++Install [httpx](https://www.python-httpx.org/) for making async HTTP requests to the Swetrix API:++```bash+pip install httpx+```++## Setup++Create a reusable Swetrix client that wraps the Events API:++```python+import httpx+from typing import Optional+++class SwetrixClient:+ def __init__(+ self,+ project_id: str,+ api_url: str = "https://api.swetrix.com/log",+ disabled: bool = False,+ ):+ self.project_id = project_id+ self.api_url = api_url+ self.disabled = disabled+ self._client = httpx.AsyncClient(timeout=10.0)++ async def track_pageview(+ self,+ ip: str,+ user_agent: str,+ *,+ pg: Optional[str] = None,+ lc: Optional[str] = None,+ ref: Optional[str] = None,+ so: Optional[str] = None,+ me: Optional[str] = None,+ ca: Optional[str] = None,+ unique: bool = False,+ ):+ if self.disabled:+ return++ payload = {"pid": self.project_id}+ if pg:+ payload["pg"] = pg+ if lc:+ payload["lc"] = lc+ if ref:+ payload["ref"] = ref+ if so:+ payload["so"] = so+ if me:+ payload["me"] = me+ if ca:+ payload["ca"] = ca+ if unique:+ payload["unique"] = True++ await self._client.post(+ self.api_url,+ json=payload,+ headers={+ "User-Agent": user_agent or "",+ "X-Client-IP-Address": ip,+ "Content-Type": "application/json",+ },+ )++ async def track_event(+ self,+ ip: str,+ user_agent: str,+ *,+ ev: str,+ pg: Optional[str] = None,+ unique: bool = False,+ meta: Optional[dict] = None,+ ):+ if self.disabled:+ return++ payload = {"pid": self.project_id, "ev": ev}+ if pg:+ payload["pg"] = pg+ if unique:+ payload["unique"] = True+ if meta:+ payload["meta"] = meta++ await self._client.post(+ f"{self.api_url}/custom",+ json=payload,+ headers={+ "User-Agent": user_agent or "",+ "X-Client-IP-Address": ip,+ "Content-Type": "application/json",+ },+ )++ async def track_error(+ self,+ ip: str,+ user_agent: str,+ *,+ name: str,+ message: Optional[str] = None,+ stack_trace: Optional[str] = None,+ pg: Optional[str] = None,+ lc: Optional[str] = None,+ meta: Optional[dict] = None,+ ):+ if self.disabled:+ return++ payload = {"pid": self.project_id, "name": name}+ if message:+ payload["message"] = message+ if stack_trace:+ payload["stackTrace"] = stack_trace+ if pg:+ payload["pg"] = pg+ if lc:+ payload["lc"] = lc+ if meta:+ payload["meta"] = meta++ await self._client.post(+ f"{self.api_url}/error",+ json=payload,+ headers={+ "User-Agent": user_agent or "",+ "X-Client-IP-Address": ip,+ "Content-Type": "application/json",+ },+ )++ async def heartbeat(self, ip: str, user_agent: str):+ if self.disabled:+ return++ await self._client.post(+ f"{self.api_url}/hb",+ json={"pid": self.project_id},+ headers={+ "User-Agent": user_agent or "",+ "X-Client-IP-Address": ip,+ "Content-Type": "application/json",+ },+ )++ async def close(self):+ await self._client.aclose()+```++:::caution+Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.+:::++## Application setup++Initialise the client and wire it into your FastAPI app using [lifespan events](https://fastapi.tiangolo.com/advanced/events/):++```python+import os+from contextlib import asynccontextmanager+from fastapi import FastAPI+++@asynccontextmanager+async def lifespan(app: FastAPI):+ app.state.swetrix = SwetrixClient(+ project_id=os.environ["SWETRIX_PROJECT_ID"],+ disabled=os.environ.get("ENVIRONMENT") != "production",+ )+ yield+ await app.state.swetrix.close()+++app = FastAPI(lifespan=lifespan)+```++## 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++```python+from fastapi import Request++[email protected]("/")+async def homepage(request: Request):+ swetrix = request.app.state.swetrix+ ip = request.client.host+ user_agent = request.headers.get("user-agent", "")++ await swetrix.track_pageview(+ ip,+ user_agent,+ pg="/",+ lc=request.headers.get("accept-language", "").split(",")[0] or None,+ ref=request.headers.get("referer"),+ )++ return {"message": "Hello World"}+```++### Middleware approach (recommended)++FastAPI middleware lets you track pageviews automatically on every request without repeating code in each route:++```python+from fastapi import Request++[email protected]("http")+async def track_pageviews(request: Request, call_next):+ swetrix = request.app.state.swetrix+ ip = request.client.host+ user_agent = request.headers.get("user-agent", "")++ # Fire-and-forget β don't block the response+ import asyncio+ asyncio.create_task(+ swetrix.track_pageview(+ ip,+ user_agent,+ pg=request.url.path,+ lc=request.headers.get("accept-language", "").split(",")[0] or None,+ ref=request.headers.get("referer"),+ )+ )++ response = await call_next(request)+ return response+```++:::tip+By using `asyncio.create_task()`, the analytics call runs in the background without adding latency to your responses. This is the recommended pattern for production.+:::++If your FastAPI app runs behind a reverse proxy (e.g. Nginx, Cloudflare, or a load balancer), configure [trusted hosts](https://fastapi.tiangolo.com/advanced/middleware/) and use the `X-Forwarded-For` header to get the real client IP:++```python[email protected]("http")+async def track_pageviews(request: Request, call_next):+ ip = request.headers.get("x-forwarded-for", "").split(",")[0].strip()+ if not ip:+ ip = request.client.host++ # ... rest of tracking logic+```++### Dependency injection approach++For more control, you can use FastAPI's dependency injection to make the client IP and user agent available in your routes:++```python+from fastapi import Depends, Request+from dataclasses import dataclass+++@dataclass+class VisitorInfo:+ ip: str+ user_agent: str+++def get_visitor_info(request: Request) -> VisitorInfo:+ ip = request.headers.get("x-forwarded-for", "").split(",")[0].strip()+ if not ip:+ ip = request.client.host+ return VisitorInfo(+ ip=ip,+ user_agent=request.headers.get("user-agent", ""),+ )++[email protected]("/dashboard")+async def dashboard(request: Request, visitor: VisitorInfo = Depends(get_visitor_info)):+ await request.app.state.swetrix.track_pageview(+ visitor.ip,+ visitor.user_agent,+ pg="/dashboard",+ )+ return {"page": "dashboard"}+```++### Pageview options++The `track_pageview` method accepts the following keyword arguments:++| Option | Type | Description |+| --- | --- | --- |+| `pg` | `str` | Page path (e.g. `/home`) |+| `lc` | `str` | Visitor locale (e.g. `en-US`) |+| `ref` | `str` | Referrer URL |+| `so` | `str` | Traffic source (e.g. `utm_source`) |+| `me` | `str` | Traffic medium (e.g. `utm_medium`) |+| `ca` | `str` | Campaign (e.g. `utm_campaign`) |+| `unique` | `bool` | Only save unique visits |++## Tracking custom events++Track specific actions β API calls, form submissions, purchases, etc.:++```python+from pydantic import BaseModel+++class SubscribeRequest(BaseModel):+ email: str+ plan: str++[email protected]("/api/subscribe")+async def subscribe(body: SubscribeRequest, request: Request):+ swetrix = request.app.state.swetrix+ ip = request.client.host+ user_agent = request.headers.get("user-agent", "")++ import asyncio+ asyncio.create_task(+ swetrix.track_event(+ ip,+ user_agent,+ ev="NEWSLETTER_SUBSCRIBE",+ pg="/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 custom exception handler to report errors to Swetrix automatically:++```python+from fastapi import Request+from fastapi.responses import JSONResponse++[email protected]_handler(Exception)+async def global_exception_handler(request: Request, exc: Exception):+ import traceback++ swetrix = request.app.state.swetrix++ import asyncio+ asyncio.create_task(+ swetrix.track_error(+ request.client.host,+ request.headers.get("user-agent", ""),+ name=type(exc).__name__,+ message=str(exc),+ stack_trace=traceback.format_exc(),+ pg=request.url.path,+ )+ )++ return JSONResponse(+ status_code=500,+ content={"error": "Internal Server Error"},+ )+```++You can also track errors from specific routes:++```python[email protected]("/api/data")+async def get_data(request: Request):+ try:+ data = await fetch_external_data()+ return data+ except Exception as exc:+ import traceback+ import asyncio++ asyncio.create_task(+ request.app.state.swetrix.track_error(+ request.client.host,+ request.headers.get("user-agent", ""),+ name=type(exc).__name__,+ message=str(exc),+ stack_trace=traceback.format_exc(),+ pg="/api/data",+ )+ )+ return JSONResponse(+ status_code=500,+ content={"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:++```python+import asyncio+from fastapi import WebSocket+++HEARTBEAT_INTERVAL = 30++[email protected]("/ws")+async def websocket_endpoint(websocket: WebSocket):+ await websocket.accept()+ ip = websocket.client.host+ user_agent = websocket.headers.get("user-agent", "")+ swetrix = websocket.app.state.swetrix++ async def send_heartbeats():+ while True:+ await swetrix.heartbeat(ip, user_agent)+ await asyncio.sleep(HEARTBEAT_INTERVAL)++ heartbeat_task = asyncio.create_task(send_heartbeats())++ try:+ while True:+ await websocket.receive_text()+ except Exception:+ heartbeat_task.cancel()+```++## Disable tracking in development++Use the `disabled` option to prevent tracking during development:++```python+swetrix = SwetrixClient(+ project_id=os.environ["SWETRIX_PROJECT_ID"],+ disabled=os.environ.get("ENVIRONMENT") != "production",+)+```++## Using environment variables for your Project ID++Rather than hardcoding the Project ID, store it in an environment variable:++```bash+export SWETRIX_PROJECT_ID=YOUR_PROJECT_ID+```++If you use a `.env` file with [python-dotenv](https://pypi.org/project/python-dotenv/):++```+SWETRIX_PROJECT_ID=YOUR_PROJECT_ID+ENVIRONMENT=production+```++```python+from dotenv import load_dotenv++load_dotenv()+```++Or with [Pydantic Settings](https://docs.pydantic.dev/latest/concepts/pydantic_settings/), which is common in FastAPI projects:++```python+from pydantic_settings import BaseSettings+++class Settings(BaseSettings):+ swetrix_project_id: str+ environment: str = "development"++ class Config:+ env_file = ".env"+++settings = Settings()++swetrix = SwetrixClient(+ project_id=settings.swetrix_project_id,+ disabled=settings.environment != "production",+)+```++## Complete example++Here's a full FastAPI application with Swetrix analytics:++```python+import os+import asyncio+import traceback+from contextlib import asynccontextmanager++import httpx+from fastapi import FastAPI, Request+from fastapi.responses import JSONResponse+from pydantic import BaseModel+++class SwetrixClient:+ def __init__(self, project_id: str, api_url: str = "https://api.swetrix.com/log", disabled: bool = False):+ self.project_id = project_id+ self.api_url = api_url+ self.disabled = disabled+ self._client = httpx.AsyncClient(timeout=10.0)++ async def track_pageview(self, ip: str, user_agent: str, **kwargs):+ if self.disabled:+ return+ payload = {"pid": self.project_id, **{k: v for k, v in kwargs.items() if v is not None}}+ await self._client.post(+ self.api_url,+ json=payload,+ headers={"User-Agent": user_agent or "", "X-Client-IP-Address": ip, "Content-Type": "application/json"},+ )++ async def track_event(self, ip: str, user_agent: str, *, ev: str, **kwargs):+ if self.disabled:+ return+ payload = {"pid": self.project_id, "ev": ev, **{k: v for k, v in kwargs.items() if v is not None}}+ await self._client.post(+ f"{self.api_url}/custom",+ json=payload,+ headers={"User-Agent": user_agent or "", "X-Client-IP-Address": ip, "Content-Type": "application/json"},+ )++ async def track_error(self, ip: str, user_agent: str, *, name: str, **kwargs):+ if self.disabled:+ return+ payload = {"pid": self.project_id, "name": name}+ if "stack_trace" in kwargs:+ kwargs["stackTrace"] = kwargs.pop("stack_trace")+ payload.update({k: v for k, v in kwargs.items() if v is not None})+ await self._client.post(+ f"{self.api_url}/error",+ json=payload,+ headers={"User-Agent": user_agent or "", "X-Client-IP-Address": ip, "Content-Type": "application/json"},+ )++ async def close(self):+ await self._client.aclose()+++@asynccontextmanager+async def lifespan(app: FastAPI):+ app.state.swetrix = SwetrixClient(+ project_id=os.environ.get("SWETRIX_PROJECT_ID", "YOUR_PROJECT_ID"),+ disabled=os.environ.get("ENVIRONMENT") != "production",+ )+ yield+ await app.state.swetrix.close()+++app = FastAPI(lifespan=lifespan)++[email protected]("http")+async def track_pageviews(request: Request, call_next):+ ip = request.headers.get("x-forwarded-for", "").split(",")[0].strip()+ if not ip:+ ip = request.client.host+ user_agent = request.headers.get("user-agent", "")++ asyncio.create_task(+ request.app.state.swetrix.track_pageview(+ ip,+ user_agent,+ pg=request.url.path,+ lc=request.headers.get("accept-language", "").split(",")[0] or None,+ ref=request.headers.get("referer"),+ )+ )++ response = await call_next(request)+ return response++[email protected]("/")+async def homepage():+ return {"message": "Hello World"}+++class ContactRequest(BaseModel):+ name: str+ email: str++[email protected]("/api/contact")+async def contact(body: ContactRequest, request: Request):+ ip = request.client.host+ user_agent = request.headers.get("user-agent", "")++ asyncio.create_task(+ request.app.state.swetrix.track_event(+ ip, user_agent, ev="CONTACT_FORM_SUBMITTED", pg="/contact"+ )+ )++ return {"success": True}++[email protected]_handler(Exception)+async def global_exception_handler(request: Request, exc: Exception):+ asyncio.create_task(+ request.app.state.swetrix.track_error(+ request.client.host,+ request.headers.get("user-agent", ""),+ name=type(exc).__name__,+ message=str(exc),+ stack_trace=traceback.format_exc(),+ pg=request.url.path,+ )+ )++ return JSONResponse(status_code=500, content={"error": "Internal Server Error"})+```++Run it with:++```bash+uvicorn main:app --reload+```++## Check your installation++Deploy your application 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 `api_url` option to your instance:++```python+swetrix = SwetrixClient(+ project_id="YOUR_PROJECT_ID",+ api_url="https://your-swetrix-instance.com/log",+)+```++## Further reading++- [Events API](/events-api) β API documentation for direct event submission.+- [FastAPI documentation](https://fastapi.tiangolo.com/) β official FastAPI docs.+- [httpx documentation](https://www.python-httpx.org/) β the async HTTP client used in this guide.diff --git a/docs/sidebars.js b/docs/sidebars.jsindex 7c14d7f43..15d9809a8 100644--- a/docs/sidebars.js+++ b/docs/sidebars.js@@ -11,6 +11,7 @@ module.exports = {label: 'Integrations',items: ['integrations/angular',+ 'integrations/aspnet','integrations/astro','integrations/bigcommerce','integrations/bubble',@@ -37,7 +38,11 @@ module.exports = {{type: 'category',label: 'Python',- items: ['integrations/django', 'integrations/flask'],+ items: [+ 'integrations/django',+ 'integrations/fastapi',+ 'integrations/flask',+ ],},'integrations/qwik',{