Blog>
Snippets

Edge-side rendering with middleware

Showcase how to use Next.js middleware for edge-side rendering to modify a response before it's sent to the client, such as A/B testing.
import { NextResponse } from 'next/server';

export function middleware(request) {
    // Randomly assign a variant for A/B testing
    const variant = Math.random() < 0.5 ? 'A' : 'B';

    // Clone the request to modify its headers
    const response = NextResponse.next();

    // Set a custom header with the variant
    response.headers.set('X-Variant', variant);

    // Return the modified response
    return response;
}
This middleware code randomly assigns a visitor to either variant 'A' or 'B' for A/B testing by setting a custom response header. This header can be used later on to determine which version of the website to serve.
import { useRouter } from 'next/router';
import { useEffect } from 'react';

export default function Page() {
    const router = useRouter();
    
    useEffect(() => {
        const variant = router.query.variant;
        if (variant === 'A') {
            // Logic for variant A
        } else if (variant === 'B') {
            // Logic for variant B
        }
    }, [router.query.variant]);

    return (
        <div>
            {/* Page content that might differ based on variant */}
        </div>
    );
}
This is a Next.js page component that uses the `useRouter` hook from Next.js to access the 'variant' query parameter set by the middleware. It applies different logic based on the variant.