reactjsnext.jscookies

How to Delete a Cookie in a Next.js 14 Middleware After External API Validation


I'm building an application with Next.js 14 and facing an issue with cookie management in my middleware. The goal is to make an external API call to validate the user's token. If the validation fails (meaning the token is invalid), I want to delete a specific cookie as it indicates the session is expired or invalid.

I've implemented a middleware function that runs verifyUser at the beginning to perform the token validation. If the token is invalid, I attempt to delete the cookie using the removeUser function. However, the cookie is not being deleted as expected.

Here's the relevant code snippet for my middleware:

import { NextResponse } from 'next/server';
import { verifyUser } from '@/lib';

export async function middleware(request) {
    await verifyUser(request)

    // Middleware logic here to proctect pages
}

export const config = {
    matcher: [
        '/',
        '/dashboard',
        '/login',
    ],
}

And here's the verifyUser function along with the removeUser function which attempts to delete the cookie:

export async function verifyUser(request) {
    // API call and token validation logic
    if (!data.success) {
        console.log('unsuccessful');
        removeUser();
    }
}

function removeUser() {
    const response = NextResponse.next();
    response.cookies.set({
        name: 'netlify',
        value: '',
        expires: new Date(0),
    })
    return response;
}

My questions are:

Any guidance or suggestions on resolving this issue would be greatly appreciated.


Solution

  • How can I correctly delete a cookie from within a middleware function in Next.js 14 when an external API indicates that the user token is invalid?

    You can use the .delete(key) method:

    function removeUser() {
        const response = NextResponse.next();
        response.cookies.delete('netlify')
        return response;
    }