How would you use middleware to redirect users based on their location or device type?
Short answer
You read information available on the request object, such as geolocation data or the user agent header, inside your middleware function, and then return a redirect response pointing to a different path if the condition matches, such as sending mobile visitors to a mobile…
Advertisement
AModel answer
You read information available on the request object, such as geolocation data or the user agent header, inside your middleware function, and then return a redirect response pointing to a different path if the condition matches, such as sending mobile visitors to a mobile optimized version of a page.
import { NextResponse } from 'next/server';
export function middleware(request) {
const country = request.geo?.country;
if (country === 'FR') {
return NextResponse.redirect(new URL('/fr', request.url));
}
}Real-world example
An online store redirects visitors from France to a dedicated French language storefront automatically, based on geolocation information read inside its middleware function.
Likely follow-ups
- Is geolocation data always accurate and available in every deployment environment?
- How do you avoid an infinite redirect loop in middleware?
Related topics