Locallytics

API Route

Set up the server-side analytics endpoint.

The locallytics() function creates the API route handlers that receive pageview data and serve analytics.

Setup

Create the API route in your Next.js app:

app/api/analytics/route.ts
import { locallytics } from "locallytics";

const analytics = await locallytics({
  database: process.env.DATABASE_URL!,
});

export const { GET, POST } = analytics;

Run migrations first

Make sure you've run npx locallytics-cli migrate before starting your app.

Configuration

OptionTypeRequiredDescription
databasestringYesDatabase connection string or file path
apiKeystringNoRequire this key for GET requests

Protected Analytics

Add an API key to protect your analytics data:

app/api/analytics/route.ts
const analytics = await locallytics({
  database: process.env.DATABASE_URL!,
  apiKey: process.env.ANALYTICS_API_KEY,
});

export const { GET, POST } = analytics;

Requests to GET /api/analytics must include the key:

curl -H "Authorization: Bearer your-api-key" \
  http://localhost:3000/api/analytics

Endpoints

POST /api/analytics

Receives pageview events from <LocallyticsGrabber />. Called automatically — you don't need to interact with this directly.

GET /api/analytics

Returns analytics data. Used internally by LocallyticsData().

Query parameters:

ParamExampleDescription
rangelast7dDate range preset
range2024-01-01,2024-01-31Custom ISO date range

Response:

{
  "pageviews": 1234,
  "uniqueVisitors": 567,
  "topPages": [{ "pageUrl": "/", "count": 500 }],
  "topReferrers": [{ "pageUrl": "google.com", "count": 200 }],
  "dailyStats": [
    { "date": "2024-01-15", "pageviews": 100, "uniqueVisitors": 50 }
  ]
}

On this page