personalization-middleware
Version:
Next.js middleware for request-based personalization
176 lines (138 loc) • 4.34 kB
Markdown
A Next.js middleware for request-based personalization that collects user context and evaluates segments. Integrates with your segmentation backend to provide real-time user segmentation based on UTM parameters, geolocation, device info, and custom attributes.
- 🔄 **Automatic Context Collection**: Device info, UTM parameters, geolocation, and more
- 🎯 **Real-time Segmentation**: Evaluate segments based on collected context
- 🚀 **Next.js Integration**: Seamless integration with Next.js middleware
- 🛡️ **Type Safety**: Full TypeScript support
- 🔌 **Flexible Backend**: Works with any segmentation backend
- 🔁 **Retry Logic**: Built-in retry mechanism with exponential backoff
- ⚡ **Performance**: Optimized for minimal impact on response times
```bash
npm install @kichijoji12/personalization-middleware
yarn add @kichijoji12/personalization-middleware
pnpm add @kichijoji12/personalization-middleware
```
1. Create a middleware file in your Next.js project:
```typescript
// middleware.ts
import { createMiddleware } from "@kichijoji12/personalization-middleware";
const personalizationMiddleware = createMiddleware({
apiEndpoint: process.env.SEGMENT_API_ENDPOINT!,
apiKey: process.env.SEGMENT_API_KEY!,
// Optional configuration
headerName: "x-user-segments", // default
timeout: 5000, // default
maxRetries: 2, // default
});
export async function middleware(request) {
return personalizationMiddleware(request);
}
export const config = {
matcher: [
/*
* Match all request paths except:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public folder
*/
"/((?!_next/static|_next/image|favicon.ico|public/).*)",
],
};
```
The middleware accepts the following configuration options:
- `apiEndpoint` (required): Your segment evaluation API endpoint
- `apiKey` (required): API key for authentication
- `headerName` (optional): Custom header name for segments (default: "x-user-segments")
- `timeout` (optional): Request timeout in milliseconds (default: 5000)
- `maxRetries` (optional): Maximum number of retry attempts (default: 2)
## Context Collection
The middleware automatically collects and structures the following context:
```typescript
interface RequestContext {
utm: {
source?: string;
medium?: string;
campaign?: string;
term?: string;
content?: string;
};
geolocation?: {
country?: string;
region?: string;
city?: string;
};
device: {
deviceType?: string;
browser?: string;
os?: string;
};
userId?: string;
sessionId?: string;
referrer?: string;
customAttributes?: {
[]: string | number | boolean | null;
};
}
```
To provide geolocation data, set the `x-geo-location` header with JSON-formatted location data:
```typescript
headers: {
"x-geo-location": JSON.stringify({
country: "US",
region: "CA",
city: "San Francisco"
})
}
```
The middleware looks for the following cookies:
- `user_id`: For persistent user identification
- `personalization_session`: For session tracking
The middleware makes a POST request to your segmentation backend with the following structure:
```typescript
// Request
{
context: RequestContext;
}
// Response
{
segments: Array<{
id: string;
name: string;
description?: string;
active?: boolean;
ruleCount?: number;
}>;
context: RequestContext;
timestamp: number;
requestId: string;
}
```
The middleware is designed to fail gracefully:
- If segment evaluation fails, the request continues without segments
- Network errors are retried with exponential backoff
- All errors are logged to the console
- After max retries, the request proceeds without segments
The package includes comprehensive TypeScript definitions. Import types as needed:
```typescript
import type {
RequestContext,
Segment,
SegmentEvaluationResult,
} from "@kichijoji12/personalization-middleware";
```
Contributions are welcome! Please feel free to submit a Pull Request.
MIT