Skip to content

Instantly share code, notes, and snippets.

@dgoerdes
Last active March 28, 2022 13:58
Show Gist options
  • Save dgoerdes/5a5ef41e3456f33da54ce6530502042f to your computer and use it in GitHub Desktop.
Save dgoerdes/5a5ef41e3456f33da54ce6530502042f to your computer and use it in GitHub Desktop.
Next.js 12 - Default Locale Prefix Middleware
// 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