Popular Frameworks
Integrating Scoby Analytics with Express
Prerequisites
- Ensure you have your License Key and Salt ready.
- Install dependencies:
npm i @scoby/analytics-ts request-ip
* Add the following lines to your `.env` file (in your project root):
```bash
SCOBY_API_KEY=your_api_key_here
SCOBY_SALT=your_generated_salt_here
```
* If your Express app runs behind a proxy or CDN, enable IP forwarding:
```js
// app.js / server.js
app.set('trust proxy', true);
```
---
## **Logging Page Views**
Scoby Analytics can log every incoming page view with minimal overhead using a simple Express middleware.
This middleware captures the visitor’s IP, User-Agent, requested URL, and referrer, then asynchronously logs the event to Scoby.
### 1. Create the middleware
```js
// middleware/scobyAnalytics.js (CommonJS)
const { Client } = require('@scoby/analytics-ts');
const { getClientIp } = require('request-ip');
const scoby = new Client(process.env.SCOBY_API_KEY, process.env.SCOBY_SALT);
// Optional: ignore internal or local traffic
scoby.blacklistIpRange('10.0.0.0/8');
scoby.blacklistIpRange('192.168.0.0/16');
scoby.blacklistIpRange('::1');
module.exports = function scobyAnalytics(req, res, next) {
const requestedUrl = `${req.protocol}://${req.get('host')}${req.originalUrl}`;
const referringUrl = req.get('referer') || req.get('referrer') || undefined;
const ipAddress = getClientIp(req) || req.ip || '0.0.0.0';
const userAgent = req.get('user-agent') || '';
// Optional: enrich with app context
const visitorId = req.user?.id;
const visitorSegments = req.user?.roles;
// Fire-and-forget — never block requests
scoby
.logPageView({
ipAddress,
userAgent,
requestedUrl,
referringUrl,
visitorId,
visitorSegments,
})
.catch(() => {});
next();
};
```
### 2. Register it globally
```js
// app.js / server.js
const express = require('express');
const scobyAnalytics = require('./middleware/scobyAnalytics');
const app = express();
app.set('trust proxy', true);
app.use(scobyAnalytics);
// your other middleware and routes...
app.listen(3000, () => console.log('Server running on port 3000'));
```
### TypeScript example
```ts
// middleware/scobyAnalytics.ts
import { Client } from '@scoby/analytics-ts';
import { getClientIp } from 'request-ip';
import type { Request, Response, NextFunction } from 'express';
const scoby = new Client(process.env.SCOBY_API_KEY!, process.env.SCOBY_SALT!);
export function scobyAnalytics(req: Request, _res: Response, next: NextFunction) {
const requestedUrl = `${req.protocol}://${req.get('host')}${req.originalUrl}`;
const referringUrl = req.get('referer') || req.get('referrer') || undefined;
const ipAddress = getClientIp(req) || req.ip || '0.0.0.0';
const userAgent = req.get('user-agent') || '';
scoby
.logPageView({
ipAddress,
userAgent,
requestedUrl,
referringUrl,
visitorId: (req as any).user?.id,
visitorSegments: (req as any).user?.roles,
})
.catch(() => {});
next();
}
```
> **Tip:**
> To retain tracking parameters like `gclid` or `fbclid`, whitelist them once at startup:
>
> ```js
> scoby.addWhitelistedUrlParameter('gclid');
> scoby.addWhitelistedUrlParameter('fbclid');
> ```
---
## **Logging Conversions**
Use `logConversion` whenever a conversion occurs — for example, after an order confirmation, signup, or lead submission.
You can log conversions **server-side** (preferred) or via a lightweight `/api/conversion` endpoint.
### 1. Create a conversion route
```js
// routes/conversions.js
const express = require('express');
const { Client } = require('@scoby/analytics-ts');
const { getClientIp } = require('request-ip');
const router = express.Router();
const scoby = new Client(process.env.SCOBY_API_KEY, process.env.SCOBY_SALT);
router.post('/conversion', async (req, res) => {
try {
const requestedUrl = `${req.protocol}://${req.get('host')}${req.originalUrl}`;
const ipAddress = getClientIp(req) || req.ip || '0.0.0.0';
const userAgent = req.get('user-agent') || '';
// Example payload: { goal: "purchase", amount: 49.99, currency: "EUR" }
const { goal, amount, currency } = req.body || {};
await scoby.logConversion({
ipAddress,
userAgent,
requestedUrl,
goal, // e.g. "purchase", "signup", "lead"
amount, // optional
currency, // optional
});
res.status(204).end();
} catch {
// Never break UX due to analytics
res.status(204).end();
}
});
module.exports = router;
```
### 2. Register the route
```js
// app.js / server.js
const express = require('express');
const scobyAnalytics = require('./middleware/scobyAnalytics');
const conversions = require('./routes/conversions');
const app = express();
app.set('trust proxy', true);
app.use(express.json());
app.use(scobyAnalytics);
app.use('/api', conversions);
app.listen(3000);
```
### 3. Trigger conversions from the frontend or backend
After a successful purchase, signup, or lead submission, call your conversion route:
```js
fetch('/api/conversion', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
goal: 'purchase',
amount: 49.99,
currency: 'EUR',
}),
keepalive: true, // avoids losing the call on page unload
});
```
### Best Practices
* Use **server-side logging** whenever possible (e.g. after database persistence or webhook confirmation).
* Avoid sending personally identifiable information (PII) to Scoby.
* Scoby automatically filters irrelevant URL parameters and anonymizes visitor identifiers using HMAC hashing.
---
With this setup, Scoby Analytics tracks both **page views** and **conversions** in your Express application—securely, efficiently, and with full control over data flow.