-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinternationalization.js
More file actions
37 lines (29 loc) · 1.03 KB
/
internationalization.js
File metadata and controls
37 lines (29 loc) · 1.03 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
// for next.js internationalization
import { NextResponse } from "next/server";
import { match } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";
const defalutLocale = "en";
const locales = ["en", "ar", "bn"];
const getLocale = (request) => {
const acceptLanguage = request.headers.get("accept-language") ?? undefined;
let headers = { "accept-language": acceptLanguage };
let languages = new Negotiator({ headers }).languages();
return match(languages, locales, defalutLocale); // -> 'en-US'
};
export const middleware = (request) => {
const pathName = request.nextUrl.pathname;
const pathNameISMissingLocale = locales.every(
(locale) =>
!pathName.startsWith(`/${locale}`) && !pathName.startsWith(`/${locale}/`)
);
if (pathNameISMissingLocale) {
const locale = getLocale(request);
return NextResponse.redirect(
new URL(`/${locale}/${pathName}`, request.url)
);
}
return NextResponse.next();
};
export const config = {
matcher: ["/((?!api|assets|.*\\..*|_next).*)"],
};