npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

personalization-middleware

v0.1.15

Published

Next.js middleware for request-based personalization

Downloads

35

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-middleware

Usage

  1. 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 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:

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 identification
  • personalization_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