1
0

middleware.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { NextResponse } from 'next/server';
  2. import type { NextRequest } from 'next/server';
  3. export function middleware(request: NextRequest) {
  4. const token = request.cookies.get('auth_token')?.value;
  5. const isLoginPage = request.nextUrl.pathname === '/login';
  6. // If no token exists and user is trying to access a protected route
  7. // Kick them to the login page immediately at the edge.
  8. if (!token && !isLoginPage) {
  9. const loginUrl = new URL('/login', request.url);
  10. return NextResponse.redirect(loginUrl);
  11. }
  12. // If token exists and they are hitting the login page, redirect to dashboard
  13. if (token && isLoginPage) {
  14. const dashboardUrl = new URL('/', request.url);
  15. return NextResponse.redirect(dashboardUrl);
  16. }
  17. return NextResponse.next();
  18. }
  19. // See "Matching Paths" below to learn more
  20. export const config = {
  21. matcher: [
  22. /*
  23. * Match all request paths except for the ones starting with:
  24. * - api (API routes)
  25. * - _next/static (static files)
  26. * - _next/image (image optimization files)
  27. * - favicon.ico (favicon file)
  28. * - images/ (public assets)
  29. * - banner.png (public assets)
  30. */
  31. '/((?!api|_next/static|_next/image|favicon.ico|images|banner).*)',
  32. ],
  33. };