47 lines
1.5 KiB
TypeScript
47 lines
1.5 KiB
TypeScript
import createMiddleware from 'next-intl/middleware';
|
|
import { NextResponse } from 'next/server';
|
|
import type { NextRequest } from 'next/server';
|
|
import { jwtVerify } from 'jose';
|
|
|
|
// Create next-intl middleware
|
|
const intlMiddleware = createMiddleware({
|
|
locales: ['tr', 'en'],
|
|
defaultLocale: 'tr',
|
|
localePrefix: 'as-needed'
|
|
});
|
|
|
|
export default async function middleware(req: NextRequest) {
|
|
// Check if it's an admin route
|
|
if (req.nextUrl.pathname.startsWith('/admin')) {
|
|
// Allow access to login page
|
|
if (req.nextUrl.pathname === '/admin/login') {
|
|
return NextResponse.next();
|
|
}
|
|
|
|
const token = req.cookies.get('admin_token')?.value;
|
|
if (!token) {
|
|
return NextResponse.redirect(new URL('/admin/login', req.url));
|
|
}
|
|
|
|
try {
|
|
const secret = new TextEncoder().encode(process.env.JWT_SECRET || 'fallback-secret-for-development-only-do-not-use-in-prod');
|
|
await jwtVerify(token, secret);
|
|
return NextResponse.next();
|
|
} catch (err) {
|
|
// Invalid token
|
|
return NextResponse.redirect(new URL('/admin/login', req.url));
|
|
}
|
|
}
|
|
|
|
// Delegate non-admin routes to next-intl
|
|
return intlMiddleware(req);
|
|
}
|
|
|
|
export const config = {
|
|
// Match all pathnames except for
|
|
// - … if they start with `/api`, `/_next`, `/_vercel`
|
|
// - … the ones containing a dot (e.g. `favicon.ico`)
|
|
// Notice we removed 'admin' from exclusion list so it passes through our custom middleware
|
|
matcher: ['/((?!api|_next|_vercel|.*\\..*).*)']
|
|
};
|