question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[Middleware] - Deleting cookies does not work.

See original GitHub issue

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System: Platform: win32 Arch: x64 Version: Windows 10 Pro Binaries: Node: 18.6.0 npm: N/A Yarn: N/A pnpm: N/A Relevant packages: next: 12.2.6-canary.8 eslint-config-next: 12.2.5 react: 18.2.0 react-dom: 18.2.0

What browser are you using? (if relevant)

Chrome 105.0.5195.52

How are you deploying your application? (if relevant)

next start

Describe the Bug

Calling request.cookies.delete(KEY) according to the documentation does not delete the cookie. The cookie is set just fine, but cannot be removed through middleware. I have tested in both dev and next start.

I also tested this in an edge API route on my actual codebase and hit the same result.

Expected Behavior

Cookie should be removed performing this operation in middleware

const response = NextResponse.next();

response.cookies.delete(KEY);

return response;

Link to reproduction

https://github.com/sannajammeh/next-middleware-cookie-delete

To Reproduce

  1. Clone the github repo
  2. Build & start next server
  3. Navigate to / which will fire useEffect to set the cookie, observe in browser devtools that its there
  4. Navigate to /remove which will trigger middleware and attempt to remove the cookie.
  5. Observe that the cookie is still there despite no calls to /api/set-cookie and console logs from middleware showing cookie is there.

Issue Analytics

  • State:open
  • Created a year ago
  • Comments:8 (2 by maintainers)

github_iconTop GitHub Comments

5reactions
sannajammehcommented, Sep 10, 2022

Here is how the docs says to do it. In that case the docs should be changed if it doesn’t delete the cookie at all.

Manual deletion worked fine for me:

export const deleteCookie = (
  request: NextRequest,
  response: NextResponse,
  cookie: string
) => {
  const cookies = request.headers.get("cookie");
  if (cookies) {
    const cookieValue = cookies
      .split(";")
      .find((c) => c.trim().startsWith(`${cookie}=`));
    if (cookieValue) {
      response.headers.set("Set-Cookie", `${cookieValue}; Max-Age=0`);
    }
  }
};

For some reason I’ve ran into some issues while testing this. Decided to refactor it a bit, no problems so far 😃

export const deleteCookie = (
  request: NextRequest,
  response: NextResponse,
  cookie: string
) => {
  const { value, options } = request.cookies.getWithOptions(cookie);
  if (value) {
    response.cookies.set(cookie, value, options);
    response.cookies.delete(cookie);
  }
};
1reaction
ricardo-rpcommented, Oct 20, 2022

I’m having success with the following workaround:

const deleteCookie = (response: NextResponse, key: string) => {
    response.cookies.set(key, "", { expires: new Date(Date.now()) });
};
Read more comments on GitHub >

github_iconTop Results From Across the Web

Laravel - Delete Cookie in Middleware - Stack Overflow
It will check if Request has a specific cookie, then delete another cookie. But it seems Cookies are not forgotten or set in...
Read more >
Express cookie-session middleware
If your session object is large enough to exceed a browser limit when encoded, in most cases the browser will refuse to store...
Read more >
ActionDispatch::Cookies - Rails API
Cookies are read and written through ActionController#cookies. The cookies being read are the ones received along with the request, the cookies being ...
Read more >
ExpressJS - Cookies - Tutorialspoint
js file; this can be used the same way as we use other middleware. Here, we will use the following code. var cookieParser...
Read more >
Using Cookie Middleware without ASP.NET Core Identity
You may want to make the cookie expire be remembered over browser sessions. You may also want an absolute expiry to the identity...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found