1

I am using Next.js version 14.1.0, and I have created a file named middleware.js in the src directory. My src folder contains the following subdirectories:

  1. app
  2. common
  3. components

Within the app directory, there is a subdirectory named student among others. I am trying to protect the student route using middleware.

Here is the content of my middleware.js file:


import { NextResponse } from 'next/server'
 
// This function can be marked `async` if using `await` inside
export function middleware(request) {

    const path = request.nextUrl.pathname

    const isPublicPath = path === '/login' || path === '/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: '/student/:path*',
}

Here is my next.config.mjs file

/** @type {import('next').NextConfig} */
const nextConfig = {
//  skipTrailingSlashRedirect: true,
//  trailingSlash: true,
//  output: 'export',

api: {
  bodyParser: {
    sizeLimit: "20mb",
  },
},

  images: {
    domains: ['20.78.10.88'],
  },

};
  
export default nextConfig;

Here is my jsconfig.json file

{
  "compilerOptions": {
    "paths": {
      "@/*": ["./src/*"]
    }
  }
}

I suspect there might be an issue related to some missing configurations in the next.config.mjs file and jsconfig.json file. What could be the possible solution to resolve this issue?

9
  • Is the token empty when the function is called? Commented May 8, 2024 at 9:26
  • @Ofirfr i am testing it in the private tab , there is no token present. i also verify by inspecting application tab in the browser Commented May 8, 2024 at 9:38
  • Can you log the values of isPublicPath and token when the page is rendered and paste them here? Commented May 8, 2024 at 9:58
  • @Ofirfr i am unable to see the log values of these variables Commented May 8, 2024 at 10:08
  • Why is that? Maybe the code is not even invoked? Please check both client and server logs Commented May 8, 2024 at 10:36

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.