Next.js Discord

Discord Forum

cache function is not a function error when using middleware

Unanswered
American Bobtail posted this in #help-forum
Open in Discord
American BobtailOP
I have nextjs with Lucia auth. In my lucia.ts file I use the cache function to save on DB reads. It works when I would not use the nextjs middleware, but when I do I see this error message

export const getPageSession = cache(() => {
  const authRequest = auth.handleRequest({
    request: null,
    cookies,
  })
  return authRequest.validate()
})


export async function middleware(request: NextRequest) {
  const pathname = request.nextUrl.pathname
  const isLoginOrSignup = routeIsLoginOrSignup(pathname)
  const isLandingPage = routeIsLandingPage(pathname)
  const authCookie = request.cookies.get("auth_session")
  if (authCookie) {
    const session = await auth.getSession(authCookie.value)
    // Logged in and trying to access landing page
    if(session.user && isLandingPage){
       return NextResponse.redirect(new URL("/dashboard", request.url))
    }
    // Logged in and trying to access login or signup page
    if (session && isLoginOrSignup) {
      return NextResponse.redirect(new URL("/dashboard", request.url))
    }
    // // Logged out and trying to access a logged in page
    if (!session && !isLoginOrSignup) {
      return NextResponse.redirect(new URL("/login", request.url))
    }
  }
  else if (!isLoginOrSignup) {
    return NextResponse.redirect(new URL("/login", request.url))
  }

  return NextResponse.next()
}

export const config = {
  matcher: "/((?!api|_next/static|_next/image|favicon.ico).*)", // Matches all routes except api routes (Route Handlers), static files, and image files
}


When I remove the session and nextresponse code from middleware the error disappears

0 Replies