forked from basehub-ai/nextjs-blog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
61 lines (52 loc) · 1.96 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
import { NextRequest, NextResponse } from "next/server";
import { match } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'
import { cookies } from "next/headers";
import { basehub } from "basehub";
// Get the preferred locale, similar to the above or using a library
async function getLocale(request: Request, locales: string[], defaultLocale: string) {
const cookieManager = await cookies()
const localeFromCookies = cookieManager.get('preferred-language')?.value
const negotiator = new Negotiator({headers: Object.fromEntries(request.headers)})
const preferredLanguages = localeFromCookies ? [localeFromCookies] : negotiator.languages()
try {
return match(preferredLanguages, locales, defaultLocale)
} catch {
return localeFromCookies ?? defaultLocale
}
}
export async function middleware(request: NextRequest) {
// Check if there is any supported locale in the pathname
const { pathname } = request.nextUrl
console.time('query to basehub')
const variants =(await basehub().query({
settings: {
language: {
variants: {
apiName: true,
isDefault: true
}
}
}
})).settings.language.variants
console.timeEnd('query to basehub')
const locales = variants.map((v) => v.apiName)
const defaultLocale = variants.find((v) => v.isDefault)?.apiName ?? 'en'
const pathnameHasLocale = locales.find(
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
)
if (pathnameHasLocale) {
const response = NextResponse.next()
response.cookies.set('preferred-language', pathnameHasLocale)
return response
}
// Redirect if there is no locale
const locale = await getLocale(request, locales, defaultLocale)
request.nextUrl.pathname = `/${locale}${pathname}`
// e.g. incoming request is /products
// The new URL is now /en-US/products
return NextResponse.redirect(request.nextUrl)
}
export const config = {
matcher: ['/((?!_next).*)'],
}