fumadocs-core
Version:
The React.js library for building a documentation website
58 lines (56 loc) • 2.06 kB
JavaScript
import { getNegotiator } from "../negotiation/index.js";
import { match } from "@formatjs/intl-localematcher";
import { NextResponse } from "next/server";
//#region src/i18n/middleware.ts
const DefaultFormatter = {
get(url) {
const segs = url.pathname.split("/");
if (segs.length > 1 && segs[1]) return segs[1];
},
add(url, locale) {
const next = new URL(url);
next.pathname = `${url.basePath}/${locale}/${url.pathname}`.replaceAll(/\/+/g, "/");
return next;
},
remove(url) {
const next = new URL(url);
const pathname = url.pathname.split("/").slice(2).join("/");
next.pathname = `${url.basePath}/${pathname}`.replaceAll(/\/+/g, "/");
return next;
}
};
function createI18nMiddleware({ languages, defaultLanguage, format = DefaultFormatter, cookieName = "FD_LOCALE", hideLocale = "never" }) {
let formatter;
if (typeof format === "function") formatter = {
...DefaultFormatter,
add(url, locale) {
const next = new URL(url);
next.pathname = format(locale, url.pathname);
return next;
}
};
else formatter = format;
return (request) => {
const url = request.nextUrl;
let pathLocale = formatter.get(url);
if (pathLocale && !languages.includes(pathLocale)) pathLocale = void 0;
if (!pathLocale) {
if (hideLocale === "default-locale") return NextResponse.rewrite(formatter.add(url, defaultLanguage));
const preferred = match(getNegotiator(request).languages(languages), languages, defaultLanguage);
if (hideLocale === "always") {
const locale = request.cookies.get(cookieName)?.value ?? preferred;
return NextResponse.rewrite(formatter.add(url, locale));
}
return NextResponse.redirect(formatter.add(url, preferred));
}
if (hideLocale === "always" || hideLocale === "default-locale" && pathLocale === defaultLanguage) {
const res = NextResponse.redirect(formatter.remove(url));
res.cookies.set(cookieName, pathLocale);
return res;
}
return NextResponse.next();
};
}
//#endregion
export { DefaultFormatter, createI18nMiddleware };
//# sourceMappingURL=middleware.js.map