personalization-middleware
v0.1.15
Published
Next.js middleware for request-based personalization
Downloads
35
Maintainers
Readme
Personalization Middleware
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.
Features
- 🔄 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
Installation
npm install @kichijoji12/personalization-middleware
# or
yarn add @kichijoji12/personalization-middleware
# or
pnpm add @kichijoji12/personalization-middlewareUsage
- Create a middleware file in your Next.js project:
// 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/).*)",
],
};Configuration
The middleware accepts the following configuration options:
apiEndpoint(required): Your segment evaluation API endpointapiKey(required): API key for authenticationheaderName(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:
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?: {
[key: string]: string | number | boolean | null;
};
}Geolocation Support
To provide geolocation data, set the x-geo-location header with JSON-formatted location data:
headers: {
"x-geo-location": JSON.stringify({
country: "US",
region: "CA",
city: "San Francisco"
})
}User Identification
The middleware looks for the following cookies:
user_id: For persistent user identificationpersonalization_session: For session tracking
Segmentation Backend Integration
The middleware makes a POST request to your segmentation backend with the following structure:
// Request
{
context: RequestContext;
}
// Response
{
segments: Array<{
id: string;
name: string;
description?: string;
active?: boolean;
ruleCount?: number;
}>;
context: RequestContext;
timestamp: number;
requestId: string;
}Error Handling
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
TypeScript Support
The package includes comprehensive TypeScript definitions. Import types as needed:
import type {
RequestContext,
Segment,
SegmentEvaluationResult,
} from "@kichijoji12/personalization-middleware";Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT
