Add i18n support with Next.js App Router and Dictionaries
This commit is contained in:
38
proxy.ts
38
proxy.ts
@@ -1,22 +1,52 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "./auth";
|
||||
import { match } from "@formatjs/intl-localematcher";
|
||||
import Negotiator from "negotiator";
|
||||
|
||||
const locales = ["tr", "en"];
|
||||
const defaultLocale = "tr";
|
||||
|
||||
function getLocale(request: Request): string {
|
||||
const headers = { "accept-language": request.headers.get("accept-language") || "" };
|
||||
const languages = new Negotiator({ headers }).languages();
|
||||
try {
|
||||
return match(languages, locales, defaultLocale);
|
||||
} catch {
|
||||
return defaultLocale;
|
||||
}
|
||||
}
|
||||
|
||||
export default auth((req) => {
|
||||
const { nextUrl } = req;
|
||||
const isLoggedIn = !!req.auth;
|
||||
const isLoginPage = nextUrl.pathname === "/login";
|
||||
const pathname = nextUrl.pathname;
|
||||
|
||||
// Check if there is any supported locale in the pathname
|
||||
const pathnameIsMissingLocale = locales.every(
|
||||
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
|
||||
);
|
||||
|
||||
// Proxy arkasında çalışırken doğru adresi alabilmek için
|
||||
const host = req.headers.get("x-forwarded-host") || req.headers.get("host") || "localhost:3000";
|
||||
const proto = req.headers.get("x-forwarded-proto") || "http";
|
||||
const baseUrl = `${proto}://${host}`;
|
||||
|
||||
// Redirect if there is no locale
|
||||
if (pathnameIsMissingLocale) {
|
||||
const locale = getLocale(req as any);
|
||||
return NextResponse.redirect(
|
||||
new URL(`/${locale}${pathname === '/' ? '' : pathname}`, baseUrl)
|
||||
);
|
||||
}
|
||||
|
||||
const currentLocale = pathname.split('/')[1] || defaultLocale;
|
||||
const isLoginPage = pathname === `/${currentLocale}/login`;
|
||||
|
||||
if (!isLoggedIn && !isLoginPage) {
|
||||
return NextResponse.redirect(new URL("/login", baseUrl));
|
||||
return NextResponse.redirect(new URL(`/${currentLocale}/login`, baseUrl));
|
||||
}
|
||||
|
||||
if (isLoggedIn && isLoginPage) {
|
||||
return NextResponse.redirect(new URL("/dashboard", baseUrl));
|
||||
return NextResponse.redirect(new URL(`/${currentLocale}/dashboard`, baseUrl));
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
|
||||
Reference in New Issue
Block a user