Next.js Middleware Integration
High-performance middleware for Next.js applications with intelligent batching and edge runtime compatibility.
Prerequisites
- Next.js 12.2+ (with middleware support)
- Node.js 16.8+
- FairCite account with Site ID and API key
Installation
Install the FairCite Next.js middleware package using your preferred package manager:
npm
npm install @faircite/nextjs-middleware
yarn
yarn add @faircite/nextjs-middleware
pnpm
pnpm add @faircite/nextjs-middleware
Quick Setup
Method 1: Environment Variables (Recommended)
First, add your credentials to your environment file:
# FairCite Configuration
FC_SITE_ID=pub_xxxxx
FC_API_KEY=fc_xxxxx
Then create your middleware file:
import { fcMiddleware } from '@faircite/nextjs-middleware';
export const middleware = fcMiddleware();
export const config = {
matcher: '/((?!_next/static|_next/image|favicon.ico).*)',
};
Method 2: Direct Configuration
Alternatively, you can pass credentials directly (not recommended for production):
import { fcMiddleware } from '@faircite/nextjs-middleware';
export const middleware = fcMiddleware({
siteId: 'pub_xxxxx', // Your FairCite site ID
apiKey: 'fc_xxxxx' // Your FairCite API key
});
export const config = {
matcher: '/((?!_next/static|_next/image|favicon.ico).*)',
};
Advanced Configuration
Configuration Options
import { fcMiddleware } from '@faircite/nextjs-middleware';
export const middleware = fcMiddleware({
// Required (if not using env vars)
siteId: 'pub_xxxxx',
apiKey: 'fc_xxxxx',
// Optional settings
edgeUrl: 'https://edge.faircite.com/v1/analyze', // Custom edge URL
enabled: true, // Enable/disable middleware
batchSize: 10, // Batch size threshold
flushInterval: 1000, // Flush interval in ms
debug: false // Enable debug logging
});
Environment Variables Reference
Variable | Description | Default |
---|---|---|
FC_SITE_ID | Your FairCite site ID | - |
FC_API_KEY | Your FairCite API key | - |
FC_EDGE_URL | Custom edge worker URL | edge.faircite.com/v1/analyze |
FC_ENABLED | Enable/disable middleware | true |
FC_BATCH_SIZE | Number of requests to batch | 10 |
FC_FLUSH_INTERVAL | Batch flush interval (ms) | 1000 |
FC_DEBUG | Enable debug logging | false |
Custom Matcher Patterns
Customize which routes are tracked by modifying the matcher configuration:
export const config = {
// Track all pages except static assets
matcher: '/((?!_next/static|_next/image|favicon.ico).*)',
// Or track specific routes only
// matcher: ['/api/:path*', '/dashboard/:path*', '/'],
// Or exclude specific routes
// matcher: '/((?!api|_next/static|_next/image|favicon.ico).*)',
};
TypeScript Support
The package includes full TypeScript support with exported types:
import type {
FairCiteConfig,
Detection,
BatchData
} from '@faircite/nextjs-middleware';
const config: FairCiteConfig = {
siteId: 'pub_xxxxx',
apiKey: 'fc_xxxxx',
batchSize: 20,
debug: process.env.NODE_ENV === 'development'
};
Testing & Verification
Development Testing
Enable debug mode to see middleware activity in your development console:
FC_DEBUG=true
Start your development server and watch the console for FairCite logs:
npm run dev
Verification Steps
- Start your Next.js application
- Navigate through several pages
- Check your browser's network tab for requests to FairCite edge
- Visit your FairCite dashboard
- Verify incoming data in the Analytics section
Performance Characteristics
Minimal Overhead
- <1ms added to request processing
- Non-blocking: Async processing doesn't delay responses
- Memory efficient: Automatic cleanup and size limits
Network Optimization
- Intelligent batching: Reduces API calls by 10-100x
- Edge compatible: Works with Vercel Edge Runtime
- Automatic retry: Built-in retry logic with exponential backoff
Deployment Considerations
Vercel Deployment
For Vercel deployments, add your environment variables in the dashboard:
- Go to your Vercel project dashboard
- Navigate to Settings → Environment Variables
- Add
FC_SITE_ID
andFC_API_KEY
- Redeploy your application
Other Platforms
The middleware works on any platform that supports Next.js:
- Netlify: Add environment variables in site settings
- Railway: Configure via environment variables panel
- Self-hosted: Set environment variables in your deployment
Troubleshooting
Middleware Not Running
- Ensure
middleware.ts
is in your project root - Verify Next.js version is 12.2 or higher
- Check that matcher patterns are correct
- Restart your development server
No Data in Dashboard
- Verify Site ID and API key are correct
- Check environment variable names (FC_SITE_ID, FC_API_KEY)
- Enable debug mode to see console logs
- Wait 1-2 minutes for data processing
Edge Runtime Issues
- The middleware is fully compatible with Edge Runtime
- Avoid Node.js specific APIs in custom configurations
- Use edge-compatible logging for debugging