Next.js Discord

Discord Forum

Remove auth cookies in middleware

Unanswered
Alaska pollock posted this in #help-forum
Open in Discord
Avatar
Alaska pollockOP
Hi,
"next": "^12.3.4",
"next-auth": "^4.22.5",

we have a remote API server that gets overwhelmed by requests with too long headers so we'd like to remove cookies included in request as they have no use at the API server that is satisfied with Bearer token. Hasn't been an issue before but after implementing SSO auth w/ Keycloak provider, returned tokens way longer than those returned by Credentials provider causing the API server to choke up returning 431 error. I've tried to remove cookies in many places including axios client-side request (interception, withCredentials: false) and middleware on server-side, but they always find a way in - confirmed by debugging a custom server where I redirected requests.
Here's what I have so far: cookies param passed to middleware include all saved cookies I would like to get rid off. Clearing them using clear() method will not help and response.cookies is empty.

import { NextResponse } from 'next/server'
import withAuth from 'next-auth/middleware'

export default withAuth(
  function middleware({ nextUrl, url, cookies }) {
    const { pathname } = nextUrl

    const firstPath = pathname.split('/')[1]

    if (firstPath === 'api') {
      const response = NextResponse.rewrite(
        new URL(
          `${'http://localhost:1234'}${pathname}${
            process.env.NODE_ENV === 'development' ? '/' : ''
          }`,
          url
        )
      )
      // clear cookies here
      
      return response
    }

    return NextResponse.next()
  },
  {
    callbacks: {
      authorized: () => true,
    },
  }
)

export const config = {
  matcher: ['/((?!_next/static|favicon.ico|).*)', '/', '/api/:path*'],
}

1 Reply

Avatar
Alaska pollockOP
Setting auth cookies to empty value not only sets cookie value in response object, but also in browser-stored cookies which is not desirable behavior, not to mention you need to know cookie names that can change (or even split to more as next-auth tries to reduce a single cookie length by splitting large values to multiple cookies with numeric sufixes - next-auth.session-token.0, next-auth.session-token.1, etc.).

response.cookies.set('next-auth.csrf-token', '')