refactor: migrate middleware.ts to proxy.ts (Next.js 16)
Renamed middleware convention to proxy as per Next.js 16 deprecation warning. - Renamed src/middleware.ts to src/proxy.ts - Renamed exported function from middleware() to proxy()
This commit is contained in:
56
src/proxy.ts
Normal file
56
src/proxy.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import type { NextRequest } from 'next/server';
|
||||
|
||||
export function proxy(request: NextRequest) {
|
||||
// Define public paths that don't require authentication
|
||||
const publicPaths = [
|
||||
'/login',
|
||||
'/api/auth/login',
|
||||
'/_next',
|
||||
'/favicon.ico',
|
||||
'/manifest.json',
|
||||
];
|
||||
|
||||
const path = request.nextUrl.pathname;
|
||||
|
||||
// Check if the path is public
|
||||
// We use startsWith to cover subpaths if necessary, but strictly usually better for pages
|
||||
// For _next, startsWith is correct. For /login, exact match is better unless we have nested public routes.
|
||||
// Let's use exact match for explicit pages and startsWith for assets/api
|
||||
const isPublicPath =
|
||||
path === '/login' ||
|
||||
path === '/api/auth/login' ||
|
||||
path === '/favicon.ico' ||
|
||||
path === '/manifest.json' ||
|
||||
path.startsWith('/_next');
|
||||
|
||||
// Check for auth token
|
||||
const authToken = request.cookies.get('auth-token');
|
||||
|
||||
// If validated (has token) and trying to access login, redirect to home
|
||||
if (authToken && path === '/login') {
|
||||
return NextResponse.redirect(new URL('/', request.url));
|
||||
}
|
||||
|
||||
// If protected and no token, redirect to login
|
||||
if (!isPublicPath && !authToken) {
|
||||
const loginUrl = new URL('/login', request.url);
|
||||
// loginUrl.searchParams.set('from', path); // We can implement return url later
|
||||
return NextResponse.redirect(loginUrl);
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: [
|
||||
/*
|
||||
* Match all request paths except for the ones starting with:
|
||||
* - api (API routes, except auth/login which is handled inside middleware)
|
||||
* - _next/static (static files)
|
||||
* - _next/image (image optimization files)
|
||||
* - favicon.ico (favicon file)
|
||||
*/
|
||||
'/((?!_next/static|_next/image|favicon.ico).*)',
|
||||
],
|
||||
};
|
||||
Reference in New Issue
Block a user