F

FairCite Documentation

Integration Guide for Publishers

Dashboard

Express.js Middleware Integration

Lightweight middleware for Express.js applications with automatic bot detection and intelligent batching.

Time Required: 5 minutesDifficulty: EasyExpress Version: 4.0+

Prerequisites

  • Node.js 14+ and Express.js 4.0+
  • FairCite account with Site ID and API key
  • Basic knowledge of Express middleware
Don't have credentials yet? Create your FairCite account first

Installation

Install the FairCite Express middleware package:

npm

npm install @faircite/express-middleware

yarn

yarn add @faircite/express-middleware

pnpm

pnpm add @faircite/express-middleware

Basic Setup

Quick Integration

Add FairCite middleware to your Express application:

app.js
import express from 'express';
import { FairCiteMiddleware } from '@faircite/express-middleware';

const app = express();

// Initialize FairCite middleware
const fairCite = new FairCiteMiddleware({
  siteId: 'pub_xxxxx',        // Your FairCite site ID
  apiKey: 'fc_xxxxx',         // Your FairCite API key
  debug: process.env.NODE_ENV === 'development'
});

// Use middleware globally (recommended)
app.use(fairCite.middleware());

// Your routes
app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.get('/api/users', (req, res) => {
  res.json({ users: [] });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Environment Variables (Recommended)

For better security, use environment variables:

.env
# FairCite Configuration
FAIRCITE_SITE_ID=pub_xxxxx
FAIRCITE_API_KEY=fc_xxxxx
FAIRCITE_DEBUG=false
app.js
import express from 'express';
import { FairCiteMiddleware } from '@faircite/express-middleware';

const app = express();

// Initialize with environment variables
const fairCite = new FairCiteMiddleware({
  siteId: process.env.FAIRCITE_SITE_ID,
  apiKey: process.env.FAIRCITE_API_KEY,
  debug: process.env.FAIRCITE_DEBUG === 'true'
});

app.use(fairCite.middleware());

// Rest of your application...

Advanced Configuration

All Configuration Options

const fairCite = new FairCiteMiddleware({
  // Required
  siteId: 'pub_xxxxx',
  apiKey: 'fc_xxxxx',
  
  // Optional settings
  edgeUrl: 'https://edge.faircite.com/v1/analyze',  // Custom edge URL
  enabled: true,                                    // Enable/disable tracking
  batchSize: 10,                                    // Requests per batch
  flushInterval: 1000,                              // Batch flush interval (ms)
  timeout: 5000,                                    // Request timeout (ms)
  debug: false,                                     // Debug logging
  
  // Custom error handler
  onError: (error) => {
    console.error('FairCite error:', error);
  }
});

Selective Route Tracking

Apply middleware to specific routes instead of globally:

import express from 'express';
import { FairCiteMiddleware } from '@faircite/express-middleware';

const app = express();
const fairCite = new FairCiteMiddleware({
  siteId: process.env.FAIRCITE_SITE_ID,
  apiKey: process.env.FAIRCITE_API_KEY
});

// Track specific routes only
app.get('/', fairCite.middleware(), (req, res) => {
  res.render('home');
});

app.get('/products/:id', fairCite.middleware(), (req, res) => {
  res.render('product', { id: req.params.id });
});

// API routes without tracking
app.get('/api/health', (req, res) => {
  res.json({ status: 'ok' });
});

Router-Level Middleware

Use with Express routers for modular applications:

import express from 'express';
import { FairCiteMiddleware } from '@faircite/express-middleware';

const router = express.Router();
const fairCite = new FairCiteMiddleware({
  siteId: process.env.FAIRCITE_SITE_ID,
  apiKey: process.env.FAIRCITE_API_KEY
});

// Apply to all routes in this router
router.use(fairCite.middleware());

router.get('/dashboard', (req, res) => {
  res.render('dashboard');
});

router.get('/profile', (req, res) => {
  res.render('profile');
});

// Mount the router
app.use('/user', router);

TypeScript Support

Full TypeScript support with type definitions:

app.ts
import express, { Request, Response } from 'express';
import { 
  FairCiteMiddleware, 
  FairCiteConfig,
  DetectionData 
} from '@faircite/express-middleware';

const app = express();

const config: FairCiteConfig = {
  siteId: process.env.FAIRCITE_SITE_ID!,
  apiKey: process.env.FAIRCITE_API_KEY!,
  batchSize: 20,
  debug: process.env.NODE_ENV === 'development'
};

const fairCite = new FairCiteMiddleware(config);
app.use(fairCite.middleware());

app.get('/', (req: Request, res: Response) => {
  res.send('Hello TypeScript!');
});

app.listen(3000);

Testing & Debugging

Enable Debug Mode

Enable detailed logging for development:

const fairCite = new FairCiteMiddleware({
  siteId: process.env.FAIRCITE_SITE_ID,
  apiKey: process.env.FAIRCITE_API_KEY,
  debug: true  // Enable debug logging
});

With debug enabled, you'll see logs like:

[FairCite] Processing request: GET /
[FairCite] Batch size: 3/10
[FairCite] Sending batch with 10 detections
[FairCite] Batch sent successfully

Custom Error Handling

const fairCite = new FairCiteMiddleware({
  siteId: process.env.FAIRCITE_SITE_ID,
  apiKey: process.env.FAIRCITE_API_KEY,
  onError: (error, req) => {
    // Custom error handling
    console.error(`FairCite error for ${req.path}:`, error);
    
    // Optional: Send to monitoring service
    // monitoring.captureError(error);
  }
});

Testing Integration

  1. Start your Express server with debug enabled
  2. Make requests to tracked routes
  3. Check console for FairCite debug logs
  4. Visit your FairCite dashboard
  5. Verify data appears in Analytics section

Common Integration Patterns

API-First Applications

// Track API endpoints
app.use('/api', fairCite.middleware());

// Skip health checks
app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

// All other API routes tracked
app.use('/api/v1', apiRouter);

Multi-Tenant Applications

// Different tracking per tenant
app.use('/:tenant', (req, res, next) => {
  const siteId = getTenantSiteId(req.params.tenant);
  const fairCite = new FairCiteMiddleware({
    siteId,
    apiKey: process.env.FAIRCITE_API_KEY
  });
  fairCite.middleware()(req, res, next);
});

Troubleshooting

Middleware Not Running

  • Ensure middleware is registered before route handlers
  • Check that siteId and apiKey are provided
  • Verify Express version compatibility (4.0+)
  • Enable debug mode to see activity logs

No Data in Dashboard

  • Check credentials are correct and active
  • Verify network connectivity to edge.faircite.com
  • Enable debug logging to see request details
  • Wait 1-2 minutes for batch processing

Performance Concerns

  • Middleware is non-blocking and lightweight
  • Increase batchSize for high-traffic applications
  • Adjust flushInterval to reduce API calls
  • Consider selective route tracking for APIs

Next Steps