A example of Middleware function to rewrite seasonal url based on user location
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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