Skip to content

Instantly share code, notes, and snippets.

@maapteh
Created January 26, 2022 20:46
Show Gist options
  • Save maapteh/47a6bd641089ab1675f28bafc1d066dc to your computer and use it in GitHub Desktop.
Save maapteh/47a6bd641089ab1675f28bafc1d066dc to your computer and use it in GitHub Desktop.
NextJS middleware using getViewportFromUserAgent
export function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
// public static stuff
if (pathname.startsWith('/images') || pathname.startsWith('/fonts')) {
return undefined;
}
// api/static/client routes NextJS stuff
if (pathname.includes('.') || pathname.startsWith('/api')) {
return undefined;
}
// prevent making internal stuff external
if (pathname.startsWith('/internal')) {
return new Response(null, { status: 404 });
}
const hostname = req.headers.get('host');
const countryCode = getCountryCode(hostname);
const defaultLanguage = 'nl';
const viewport = getViewportFromUserAgent(req.headers.get('user-agent'));
// We are on NL website, uses nl-NL internally only!
if (countryCode === 'nl') {
if (pathname.startsWith('/nl')) {
return new Response(null, { status: 404 });
}
return NextResponse.rewrite(`/internal/${viewport}/nl-NL${pathname}`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment