-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmiddleware.ts
67 lines (56 loc) · 2.32 KB
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import type {NextRequest} from 'next/server'
import {NextResponse} from 'next/server'
import {i18n, Locale} from '@/i18n.config'
import {match as matchLocale} from '@formatjs/intl-localematcher'
import Negotiator from "negotiator";
function getLocale(request: NextRequest): string | undefined {
const negotiatorHeaders: Record<string, string> = {}
request.headers.forEach((value, key) => (negotiatorHeaders[key] = value))
// @ts-ignore locales are readonly
const locales: string[] = i18n.locales
const languages = new Negotiator({ headers: negotiatorHeaders }).languages()
return matchLocale(languages, locales, i18n.defaultLocale)
}
export function middleware(request: NextRequest) {
//console.log("request.url ", request.url);
const pathname = new URL(request.url).pathname ? new URL(request.url).pathname : `/${new URL(request.url).pathname}`;
if (pathname.startsWith("/_next")) return;
if (pathname.startsWith("/api")) return;
if (pathname.startsWith("/static")) return;
if (pathname.startsWith("/favicon")) return;
if (pathname.startsWith("/manifest")) return;
if (pathname.startsWith("/robots")) return;
// check if the pathname is a resource file
const isResourceFile = pathname.match(/\.[0-9a-z]+$/i);
if (isResourceFile) return;
const pathnameIsMissingLocale = i18n.locales.every(
locale => !pathname.startsWith(`/${locale}`) && pathname !== `/${locale}`
)
console.log("request.url ", request.url);
if (request.nextUrl.pathname.endsWith("/fr/") || request.nextUrl.pathname.endsWith("/fr")) {
return NextResponse.redirect(
new URL(
`/fr-FR`,
request.url
)
)
}
// console.log("pathnameIsMissingLocale ", pathnameIsMissingLocale);
// console.log("pathname ", pathname);
// Redirect if there is no locale
if (pathnameIsMissingLocale) {
const locale = getLocale(request) as Locale;
console.log("redirecting " + pathname + " to " + `/${locale}${pathname.startsWith('/') ? '' : '/'}${pathname}`);
return NextResponse.redirect(
new URL(
`/${locale}${pathname.startsWith('/') ? '' : '/'}${pathname}`,
request.url
)
)
}
}
export const config = {
matcher: [
'/:path*',
]
}