I am currently working on developing a user authentication system that includes features for Login, Signup, and Logout. As part of this project, I have created a middleware.ts file in the src directory, which is located next to the app directory.
Below is the content of my middleware.ts file along with its path: (path: src/middleware.ts)
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest)
{
const path = request.nextUrl.pathname;
const isPublicPath = path.includes('/login') || path.includes('/signup');
const token = request.cookies.get('token')?.value || '';
if(isPublicPath && token)
{
return NextResponse.redirect(new URL('/', request.nextUrl));
}
if(!isPublicPath && !token)
{
return NextResponse.redirect(new URL('/login', request.nextUrl));
}
}
export const config = {
matcher:[
'/',
'/profile',
'/login',
'signup',
],
}
Upon starting the server, I encountered the following errors:
source does not start with / for route {"source":"signup"}
Subsequently, another error occurred:
Invalid middleware found.
Despite attempting to resolve these issues by saving all changes and restarting the server, the problems persisted. Similar connectivity issues had arisen previously, but after making some adjustments, the server eventually connected successfully.