Next.js Discord

Discord Forum

middleware issue

Answered
Dalmatian posted this in #help-forum
Open in Discord
DalmatianOP
I have this middleware:
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
    console.log("Middleware executing. path:", request.nextUrl.pathname)
    const token = request.cookies.get('jwt')?.value || request.cookies.get('refresh')?.value

    const protectedRoutes = ['/account', '/cart']
    const isProtectedRoute = protectedRoutes.some(route => 
        request.nextUrl.pathname.startsWith(route)
    )

    if (isProtectedRoute && !token) {
        return NextResponse.redirect(new URL('/sign-in', request.url))
    }

    return NextResponse.next()
}

export const config = {
    matcher: ['/account', '/cart']
}
but it does not work when the current path is '/account' or '/cart', even the log from the top is not being shown. How to fix that?
Answered by LuisLl
I replicated your issue, version 15.2.0, added logs in pages and middleware and this is the result:
Green: First I had a token in *jwt *cookie so middleware granted me access
Red: I deleted the *jwt *cookie and I tried accessing the pages again, redirected me

My thought is you're placing the middleware.ts file somewhere Next.js can't reach it. It needs to be inside the /src/ directory:
./src/middleware.ts.

Or in the root directory if you don’t have the /src/ folder:
./middleware.ts
View full answer

10 Replies

Where are you placing the middleware.ts file?
I replicated your issue, version 15.2.0, added logs in pages and middleware and this is the result:
Green: First I had a token in *jwt *cookie so middleware granted me access
Red: I deleted the *jwt *cookie and I tried accessing the pages again, redirected me

My thought is you're placing the middleware.ts file somewhere Next.js can't reach it. It needs to be inside the /src/ directory:
./src/middleware.ts.

Or in the root directory if you don’t have the /src/ folder:
./middleware.ts
Answer
@LuisLl Where are you placing the middleware.ts file?
DalmatianOP
I’m placing it in the root directory
DalmatianOP
Ah, so it should be in the /src directory?
@Dalmatian Ah, so it should be in the /src directory?
Yes, if your project has the src/ directory it should be in there.
@Dalmatian Solved?
@LuisLl <@589517424093691905> Solved?
DalmatianOP
Yes, thank you
Sure! Happy to help:P
Mark the solution for others to find it!