Skip to content

Instantly share code, notes, and snippets.

@neilkillen
Created August 7, 2022 22:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neilkillen/fec27af51afd8e527d7520d8e9c916b7 to your computer and use it in GitHub Desktop.
Save neilkillen/fec27af51afd8e527d7520d8e9c916b7 to your computer and use it in GitHub Desktop.
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 && req.geo.country) || '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