55 lines
2.0 KiB
TypeScript
55 lines
2.0 KiB
TypeScript
import createMiddleware from 'next-intl/middleware';
|
|
import { type NextRequest, NextResponse } from 'next/server';
|
|
import { routing } from './src/i18n/routing';
|
|
import { COOKIE_NAMES } from './src/lib/cookies';
|
|
import { isTokenAlive } from './src/lib/auth/token';
|
|
import { HEADER_NAMES, PUBLIC_PATHS, ROUTES } from './src/constants';
|
|
|
|
const intlMiddleware = createMiddleware(routing);
|
|
|
|
export default function middleware(request: NextRequest) {
|
|
const i18nResponse = intlMiddleware(request);
|
|
|
|
// If next-intl is issuing a locale normalization redirect, let it through immediately
|
|
if (i18nResponse.status === 307 || i18nResponse.status === 308) {
|
|
return i18nResponse;
|
|
}
|
|
|
|
const { pathname } = request.nextUrl;
|
|
|
|
// Strip the locale segment to get the actual path (e.g. /fa/login → /login)
|
|
const pathWithoutLocale = '/' + pathname.split('/').slice(2).join('/');
|
|
|
|
const isPublic = PUBLIC_PATHS.some((p) => pathWithoutLocale.startsWith(p));
|
|
|
|
if (!isPublic) {
|
|
const token = request.cookies.get(COOKIE_NAMES.ACCESS_TOKEN)?.value;
|
|
if (!isTokenAlive(token)) {
|
|
const locale = request.cookies.get('NEXT_LOCALE')?.value ?? routing.defaultLocale;
|
|
return NextResponse.redirect(new URL(`/${locale}${ROUTES.LOGIN}`, request.url));
|
|
}
|
|
}
|
|
|
|
// Detect locale from the normalized URL (next-intl always puts it at position 1)
|
|
const locale = routing.locales.find(
|
|
(l) => pathname === `/${l}` || pathname.startsWith(`/${l}/`),
|
|
) ?? routing.defaultLocale;
|
|
|
|
const requestHeaders = new Headers(request.headers);
|
|
requestHeaders.set(HEADER_NAMES.LOCALE, locale);
|
|
|
|
const response = NextResponse.next({ request: { headers: requestHeaders } });
|
|
|
|
// Preserve response headers set by next-intl (e.g. Link: alternate hreflang)
|
|
i18nResponse.headers.forEach((value, key) => {
|
|
response.headers.set(key, value);
|
|
});
|
|
|
|
return response;
|
|
}
|
|
|
|
export const config = {
|
|
// Match all pathnames except internal Next.js paths, API routes, and static files
|
|
matcher: ['/((?!_next|_vercel|api|.*\\..*).*)'],
|
|
};
|