58 lines
1.7 KiB
TypeScript
58 lines
1.7 KiB
TypeScript
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 pathname = nextUrl.pathname;
|
|
|
|
// Check if there is any supported locale in the pathname
|
|
const pathnameIsMissingLocale = locales.every(
|
|
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
|
|
);
|
|
|
|
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(`/${currentLocale}/login`, baseUrl));
|
|
}
|
|
|
|
if (isLoggedIn && isLoginPage) {
|
|
return NextResponse.redirect(new URL(`/${currentLocale}/dashboard`, baseUrl));
|
|
}
|
|
|
|
return NextResponse.next();
|
|
});
|
|
|
|
export const config = {
|
|
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
|
|
};
|