-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.js
More file actions
61 lines (49 loc) · 1.43 KB
/
Copy pathproxy.js
File metadata and controls
61 lines (49 loc) · 1.43 KB
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 { match } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'
import { NextResponse } from "next/server";
const locales = ['en', 'fr']
const defaultLocale = locales[0]
const localeReady = new Set([
...locales,
'download',
'img'
])
// Get the preferred locale, similar to the above or using a library
function getLocale(request) {
const h = 'accept-language'
const headers = { [h]: request.headers.get(h) }
const nego = new Negotiator({ headers })
const languages = nego.languages()
return match(languages, locales, defaultLocale)
}
export function proxy(request) {
// Check if there is any supported locale in the pathname
const { pathname } = request.nextUrl
const re = /^\/([^\/?#]*)/.exec(pathname)
if (!re) return
const restOfPath = pathname.substring(re[1].length+1)
if (localeReady.has(re[1])) return
// We need to redirect
switch (re[1].toLowerCase()) {
/* cases where we want to rename the locale, so old url's still work */
case 'fr-fr': {
request.nextUrl.pathname = `/fr${restOfPath}`
} break
case 'en-us':
case 'en-gb': {
request.nextUrl.pathname = `/en${restOfPath}`
} break
/* cases where the locale wasn't specified and we need to _add_ it */
default: {
const locale = getLocale(request)
request.nextUrl.pathname = `/${locale}${pathname}`
}
}
return NextResponse.redirect(request.nextUrl)
}
export const config = {
matcher: [
'/((?!_next).*)',
'/'
],
}