-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
42 lines (34 loc) · 1.35 KB
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
console.log('Middleware triggered for path:', pathname);
// Skip middleware for static files and special routes
if (
pathname.startsWith('/_next') || // Static files (CSS, JS, etc.)
pathname.startsWith('/api') || // API routes
pathname === '/favicon.ico' || // Favicon
pathname === '/robots.txt' || // Robots.txt
pathname === '/sitemap.xml' || // Sitemap (if applicable)
/\.(jpg|jpeg|png|gif|svg|webp|ico|css|js|woff|woff2|ttf|eot|otf)$/.test(
pathname
)
) {
return NextResponse.next();
}
// Supported language prefixes
const supportedLanguages = ['en', 'pl', 'ua'];
// Check if the path starts with any supported language and has more than just the language segment
const isValidLang = supportedLanguages.some((lang) => {
return pathname.startsWith(`/${lang}/`) || pathname === `/${lang}`;
});
// If the path is valid but has extra segments like /en/asdf, redirect to /en
if (!isValidLang || pathname.split('/').length > 2) {
return NextResponse.redirect(new URL('/en', request.url));
}
return NextResponse.next();
}
// Matcher configuration (optional, simplifies logic)
export const config = {
matcher: '/:path*',
};