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:
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
| Option | Type | Required | Description |
|---|---|---|---|
database | string | Yes | Database connection string or file path |
apiKey | string | No | Require this key for GET requests |
Protected Analytics
Add an API key to protect your analytics data:
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/analyticsEndpoints
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:
| Param | Example | Description |
|---|---|---|
range | last7d | Date range preset |
range | 2024-01-01,2024-01-31 | Custom 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 }
]
}