Last active
March 28, 2022 13:58
-
-
Save dgoerdes/5a5ef41e3456f33da54ce6530502042f to your computer and use it in GitHub Desktop.
Next.js 12 - Default Locale Prefix Middleware
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
// pages/_middleware.ts | |
import { NextRequest, NextResponse } from 'next/server'; | |
const PUBLIC_FILE = /\.([a-zA-Z0-9]+$)/; | |
export function middleware(request: NextRequest) { | |
// We need to clean up the pathName as for some reason the vercel hosted | |
// middleware gets the locale in the path. | |
// This is not the case when the code runs locally. | |
const cleanPathName = request.nextUrl.pathname.startsWith('/default') | |
? request.nextUrl.pathname.replace('/default', '/').replace('//', '/') | |
: request.nextUrl.pathname; | |
const shouldHandleLocale = | |
!PUBLIC_FILE.test(cleanPathName) && | |
!cleanPathName.includes('/api/') && | |
request.nextUrl.locale === 'default'; | |
return shouldHandleLocale | |
? NextResponse.redirect(new URL(`/en${cleanPathName}`, request.url)) | |
: undefined; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment