mediahub-fe/middleware.ts

74 lines
2.3 KiB
TypeScript
Raw Normal View History

import createMiddleware from "next-intl/middleware";
import { NextRequest, NextResponse } from "next/server";
2025-05-22 09:53:54 +00:00
import { routing } from "./i18n/routing";
2024-11-26 03:09:48 +00:00
2025-11-13 10:46:23 +00:00
const intlMiddleware = createMiddleware(routing);
2025-11-13 10:46:23 +00:00
export default function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
2024-11-26 03:09:48 +00:00
2025-11-14 02:26:50 +00:00
// --- IGNORE STATIC ASSET ---
2025-11-13 16:59:06 +00:00
const isStaticAsset =
2025-11-13 10:46:23 +00:00
pathname.startsWith("/api") ||
pathname.startsWith("/_next") ||
pathname.startsWith("/favicon") ||
2025-11-13 16:59:06 +00:00
pathname.startsWith("/assets") ||
pathname.startsWith("/static") ||
2025-11-14 02:26:50 +00:00
pathname.match(/\.(png|jpg|jpeg|gif|webp|svg|ico|css|js)$/);
2025-11-13 16:59:06 +00:00
2025-11-14 02:26:50 +00:00
if (isStaticAsset) return NextResponse.next();
// --- LOCALES YANG VALID ---
const locales = ["in", "en"];
// Ambil locale utama dari URL
const firstSegment = pathname.split("/")[1];
const isLocaleURL = locales.includes(firstSegment);
2024-11-26 03:09:48 +00:00
2025-11-14 02:26:50 +00:00
// Jika URL sudah mengandung locale → JALANKAN next-intl
if (isLocaleURL) {
2025-11-13 10:46:23 +00:00
return intlMiddleware(request);
}
2025-05-22 09:53:54 +00:00
2025-11-14 02:26:50 +00:00
// Jika URL TIDAK ada locale → redirect ke /in/<path>
2025-11-13 10:46:23 +00:00
const url = request.nextUrl.clone();
url.pathname = `/in${pathname}`;
return NextResponse.redirect(url);
}
2025-11-14 02:26:50 +00:00
// Matcher untuk semua route kecuali static files
2024-11-26 03:09:48 +00:00
export const config = {
2025-11-14 02:26:50 +00:00
matcher: ["/((?!_next|api|favicon.ico|assets|static).*)"],
};
2025-11-13 10:46:23 +00:00
// import createMiddleware from "next-intl/middleware";
// import { NextRequest, NextResponse } from "next/server";
// import { locales } from "@/config";
// import { routing } from "./i18n/routing";
// // export default async function middleware(request: NextRequest) {
// // // Step 1: Use the incoming request (example)
// // const defaultLocale = "in";
// // // const defaultLocale = request.headers.get("dashcode-locale") || "in";
// // // Step 2: Create and call the next-intl middleware (example)
// // const handleI18nRouting = createMiddleware({
// // locales: ["in", "en"],
// // defaultLocale: "in",
// // });
// // const response = handleI18nRouting(request);
// // // Step 3: Alter the response (example)
// // response.headers.set("dashcode-locale", defaultLocale);
// // return response;
// // }
// export default createMiddleware(routing);
// export const config = {
// // Match only internationalized pathnames
// matcher: ["/", "/(in|en)/:path*"],
// };