Created
January 26, 2022 20:46
-
-
Save maapteh/47a6bd641089ab1675f28bafc1d066dc to your computer and use it in GitHub Desktop.
NextJS middleware using getViewportFromUserAgent
This file contains hidden or 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
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