Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A example of Middleware function to rewrite seasonal url based on user location
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
// Trigger this middleware to run on the `/seasonal` route
export const config = {
matcher: '/seasonal',
** Middleware Function to rewrite seasonal url based on user geo location
* @param req
* @returns NextResponse with a rewrite set
export function middleware(req: NextRequest) {
// Extract country from Request Geo object. Default to US if not found and write to console
const country = (req.geo && || 'US';
console.log(`Visitor from ${country}`);
// Extract Latitude from request Geo object and determine Hemisphere
const hemisphere = (req.geo && req.geo.latitude) as any > 0 ? 'Northern' : 'Southern';
console.log(`Visitor located in ${hemisphere} Hemisphere`);
// Obtain Season using Visitor Hemisphere
let season = getSeason(hemisphere);
req.nextUrl.pathname = `/seasonal/${season}`;
console.log(`Rewrite path based on Visitor season: ${req.nextUrl.pathname}`);
// Rewrite URL to personalize visitor journey based on season
return NextResponse.rewrite(req.nextUrl);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment