Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 0 additions & 4 deletions examples/nuxt-v3/middleware/tracking-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,5 @@ export default defineNuxtRouteMiddleware(async (to) => {
return;
}

if (to.path.startsWith("/api/")) {
return;
}

await trackPageview();
});
9 changes: 3 additions & 6 deletions examples/nuxt-v3/server/api/track-event.post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,9 @@ import { defineEventHandler, createError } from "h3";

export default defineEventHandler(async (event) => {
try {
await trackEvent("button_clicked", {
event,
metadata: {
source: "test_page",
},
});
await trackEvent(event, "button_clicked", {
external_id: "1234",
});

return {
success: true,
Expand Down
4 changes: 0 additions & 4 deletions examples/nuxt-v4/app/middleware/tracking-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,5 @@ export default defineNuxtRouteMiddleware(async (to) => {
return;
}

if (to.path.startsWith("/api/")) {
return;
}

await trackPageview();
});
7 changes: 2 additions & 5 deletions examples/nuxt-v4/server/api/track-event.post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,8 @@ import { defineEventHandler, createError } from "h3";

export default defineEventHandler(async (event) => {
try {
await trackEvent("button_clicked", {
event,
metadata: {
source: "test_page",
},
await trackEvent(event, "button_clicked", {
external_id: "1234",
});

return {
Expand Down
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@
"format": "prettier --write \"**/*.{ts,tsx,md}\""
},
"devDependencies": {
"@changesets/cli": "^2.29.5",
"turbo": "^2.5.5"
"turbo": "^2.5.6"
},
"packageManager": "pnpm@10.15.1"
}
181 changes: 114 additions & 67 deletions packages/nuxt/README.md
Original file line number Diff line number Diff line change
@@ -1,108 +1,135 @@
# Simple Analytics for Nuxt
# Simple Analytics Nuxt Module

This Nuxt module provides a simple way to add privacy-friendly pageview and event tracking using Simple Analytics to your Nuxt 3 or 4 application.
A Nuxt module for integrating Simple Analytics with server-side tracking capabilities.

## Installation
## Quick Setup

```bash
npm i @simpleanalytics/nuxt
```

## Environment Variables

Set your website domain (as added in your [Simple Analytics dashboard](https://dashboard.simpleanalytics.com/)):
Install the module to your Nuxt application:

```txt
SIMPLE_ANALYTICS_HOSTNAME=example.com
```bash
npm install @simpleanalytics/nuxt
```

## Configuration

Add the module to your `nuxt.config.ts` and optionally set your hostname:
Add the module to your `nuxt.config.ts`:

```ts
// nuxt.config.ts
export default defineNuxtConfig({
// ...
modules: ["@simpleanalytics/nuxt"],
simpleAnalytics: {
hostname: "example.com", // optional, if you don't use SIMPLE_ANALYTICS_HOSTNAME
hostname: "your-domain.com",
enabled: true,
},
});
```

## Usage

### Client-side analytics
Adding the module will automatically enable client-side page view collection though the Simple Analytics script.

The module uses the `simple-analytics-vue` plugin to auto-inject the Simple Analytics script.
### Server-side Pageview Tracking

### Tracking events in client components

To track events programmatically, inject the `saEvent` function.
Track pageviews automatically on the server:

```vue
<script setup>
import { inject } from "vue";

const saEvent = inject("saEvent");

// e.g.: send event when liking a comment
const likeComment = (comment) => {
saEvent(`comment_like_${comment.id}`);
};
</script>
```

### Server-side tracking (SSR & API)

Track page views or events during server side rendering or in API routes:

#### In server-rendered pages

```vue
<script setup lang="ts">
// This will run on the server and track the pageview
if (import.meta.server) {
await trackPageview({
metadata: {
source: "some extra context",
},
some_extra_metadata: "homepage"
});
}
</script>
```

#### In Nitro API routes
### Server-side Event Tracking

Track custom events from API routes or server-side code:

```ts
// server/api/signup.post.ts
// In a (Nitro) server API route
export default defineEventHandler(async (event) => {
await trackEvent("user_signup", {
event,
metadata: {
source: "registration_form",
user_type: "new",
},
await trackEvent(event, "user_signup", {
source: "registration_form",
user_type: "new",
});

// ...
return { success: true };
});
```

## Configuration

### Module Options

```ts
export default defineNuxtConfig({
simpleAnalytics: {
// Your Simple Analytics hostname
hostname: "your-domain.com",

// Enable/disable the module
enabled: true,

// Auto-collect events
autoCollect: true,

// Collect data even when DNT is enabled
collectDnt: false,

// Dashboard mode
mode: "dash",

// Ignore specific metrics
ignoreMetrics: {
referrer: false,
utm: false,
country: false,
session: false,
timeonpage: false,
scrolled: false,
useragent: false,
screensize: false,
viewportsize: false,
language: false,

// Use vendor specific timezone headers to the determine the visitors location (server only)
timezone: false
},

// Ignore specific pages
ignorePages: ["/admin", "/private"],

// Allow specific URL parameters
allowParams: ["ref", "source"],

// Non-unique parameters
nonUniqueParams: ["utm_source"],

// Strict UTM parameter parsing
strictUtm: true,

// Enable enhanced bot detection during server tracking (server only)
enhancedBotDetection: false
},
});
```

## API Reference
### Environment Variables

```bash
# Required: Your Simple Analytics hostname
SIMPLE_ANALYTICS_HOSTNAME=your-domain.com
```

## API Reference (Nuxt)

### `trackPageview(options)`

Track a pageview on the server.

**Parameters:**

- `options` (object):
- `hostname` (string): Your Simple Analytics hostname
- `metadata` (object): Additional metadata to track
- `ignoreMetrics` (object): Metrics to ignore for this pageview
- `collectDnt` (boolean): Whether to collect data when DNT is enabled
- `strictUtm` (boolean): Whether to use strict UTM parameter parsing
- `metadata` (object): Additional metadata to track (optional)

### `trackEvent(eventName, options)`

Expand All @@ -111,9 +138,29 @@ Track a custom event on the server.
**Parameters:**

- `eventName` (string): Name of the event to track
- `options` (object):
- `headers` (Headers): Request headers
- `hostname` (string): Your Simple Analytics hostname
- `metadata` (object): Additional metadata to track
- `ignoreMetrics` (object): Metrics to ignore for this event
- `collectDnt` (boolean): Whether to collect data when DNT is enabled
- `metadata` (object): Additional metadata to track (optional)

## API Reference (Nitro)

### `trackPageview(event, options)`

Track a pageview on the server.

**Parameters:**

- `event` (H3Event): Nitro request event
- `metadata` (object): Additional metadata to track (optional)

### `trackEvent(event, eventName, options)`

Track a custom event on the server.

**Parameters:**

- `event` (H3Event): Nitro request event
- `eventName` (string): Name of the event to track
- `metadata` (object): Additional metadata to track (optional)

## License

MIT License - see the [LICENSE](LICENSE) file for details.
15 changes: 8 additions & 7 deletions packages/nuxt/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@simpleanalytics/nuxt",
"version": "1.0.1",
"version": "2.0.0",
"description": "Simple Analytics Nuxt",
"repository": "simpleanalytics/simpleanalytics-nuxt",
"license": "MIT",
Expand Down Expand Up @@ -37,20 +37,21 @@
},
"dependencies": {
"@nuxt/kit": "^4.0.3",
"simple-analytics-vue": "^3.0.3"
"simple-analytics-vue": "^3.1.0"
},
"devDependencies": {
"@nuxt/devtools": "^2.6.2",
"@nuxt/eslint-config": "^1.8.0",
"@nuxt/devtools": "^2.6.3",
"@nuxt/eslint-config": "^1.9.0",
"@nuxt/module-builder": "^1.0.2",
"@nuxt/schema": "^4.0.3",
"@nuxt/test-utils": "^3.19.2",
"@types/node": "^24.2.1",
"@types/node": "^24.3.0",
"changelogen": "^0.6.2",
"eslint": "^9.33.0",
"eslint": "^9.34.0",
"nuxt": "^4",
"typescript": "~5.9.2",
"vitest": "^3.2.4",
"vue-tsc": "^3.0.5"
"vue-tsc": "^3.0.5",
"vue": "^3"
}
}
3 changes: 3 additions & 0 deletions packages/nuxt/playground/nuxt.config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
export default defineNuxtConfig({
modules: ["../src/module"],
devtools: { enabled: true },
simpleAnalytics: {
hostname: "playground.example.com",
},
});
6 changes: 2 additions & 4 deletions packages/nuxt/playground/server/api/track-event.post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@ export default defineEventHandler(async (event) => {
const { eventName, metadata } = await readBody(event);

// Track the custom event using server-side function
await trackEvent(eventName, {
event,
metadata,
hostname: "playground.example.com",
await trackEvent(event, eventName, {
...metadata,
});

return {
Expand Down
8 changes: 5 additions & 3 deletions packages/nuxt/src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
addServerImports,
addPlugin,
} from "@nuxt/kit";
import type { SimpleAnalyticsOptions } from "./runtime/server/lib/options";
import type { SimpleAnalyticsOptions } from "./runtime/interfaces";

export interface ModuleOptions extends SimpleAnalyticsOptions {
enabled?: boolean;
Expand Down Expand Up @@ -39,23 +39,25 @@ export default defineNuxtModule<ModuleOptions>({

addPlugin(resolver.resolve("./runtime/plugin"));

// Server rendering imports
addImports([
{
name: "trackEvent",
from: resolver.resolve("./runtime/track-event"),
from: resolver.resolve("./runtime/server/track-event"),
meta: {
description: "Track a custom event with Simple Analytics",
},
},
{
name: "trackPageview",
from: resolver.resolve("./runtime/track-pageview"),
from: resolver.resolve("./runtime/server/track-pageview"),
meta: {
description: "Track a pageview with Simple Analytics",
},
},
]);

// Nitro imports
addServerImports([
{
name: "trackEvent",
Expand Down
Loading
Loading