kristina malozh
kristina malozh

Reputation: 31

Unable to Delete Cookies in Next.js Middleware

am working on a Next.js application where I am using a middleware to check if a user's token has expired. If the token has expired, I want to clear and delete the cookies and redirect the user to the login page. Here's the relevant part of my code:

export async function middleware(request: NextRequest) {
  const path = request.nextUrl.pathname;
  const token = request.cookies.get('token')?.value || '';
  const url = `${process.env.NEXT_PUBLIC_BASE_URL}users/auth/check-token-expiration`;

  let tokenExpirationData;

  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        token,
      }),
    });

    if (response.ok) {
      tokenExpirationData = await response.json();
      console.log(tokenExpirationData?.data);
    } else {
      console.error('Error occurred while fetching data:', response.statusText);
    }
  } catch (error) {
    console.error('Error occurred:', error);
  }

  if (path !== '/login' && tokenExpirationData && tokenExpirationData.data) {
    request.cookies.clear();
    request.cookies.delete('token'); // This line doesn't work as expected
    return NextResponse.redirect(new URL('/login', request.nextUrl));
  }

}

In the code above, I'm trying to clear and delete the 'token' cookie when the user's token has expired. However, the request.cookies.delete('token') line doesn't seem to remove the cookie. The user is still able to access restricted pages even after the token has expired.

I've checked the logic, and it correctly identifies when the token has expired and triggers the redirection to the login page. But the cookie deletion doesn't work.

What could be the issue here? Am I missing something in my implementation? Any help would be greatly appreciated.

Upvotes: 3

Views: 1582

Answers (1)

k32y
k32y

Reputation: 427

The issue is because you are deleting the wrong cookie.

From your code snippet, you are deleting cookie from request but this has no effect on the actual cookies returned from the middleware.

What you want to do is delete the cookies from the response object instead. Like so:

// create the response object
const response = NextResponse.redirect(new URL('/login', request.url))
 
// Delete the token cookie
response.cookies.delete('token')

// Return the response
return response

Upvotes: 3

Related Questions