Skip to content

session.destroy() on Next 14 Server Action (POST) doesn't clear cookie (no Set-Cookie in response headers) #910

@fmaiabatista

Description

@fmaiabatista

Hi,

I'm having an issue for a while on my app remote envs (prod and stg) (local works fine) that my Next 14 Server Action logout() which calls session.destroy() is not working properly. The POST request doesn't seem to include the necessary Set-Cookie that clears the session cookie, and so the users are not able to log out. What makes it more difficult to debug is that the problem is inconsistent, and I was able to release a fix which worked for a while, but then it didn't!

// src/actions/auth.tsx

"use server"

export async function getSession() {
  const session = await getIronSession<SessionData>(cookies(), sessionOptions);

  if (!session.loggedIn) {
    session.loggedIn = defaultSession.loggedIn;
    session.accessToken = defaultSession.accessToken;
  }

  return session;
}

// ...

export async function logout() {
  const session = await getSession();
  session.destroy();
  revalidatePath(ROUTES.HOME);
  return { success: true };
}

This is called from a client component in a form:

// client.tsx (simplified)

import { logout } from "../../../../../../actions/auth";

const [state, action] = useFormState(logout, undefined);

<form action={action}>
  <LogoutFormSubmitButton />
</form>

My session options are:

// lib/session/session.ts

// ...

export const sessionOptions: SessionOptions = {
  password: process.env.SESSION_SECRET as string,
  cookieName: "session",
  cookieOptions: {
    secure: process.env.NODE_ENV === "production",
    expires: new Date(Date.now() + 1000 * 60 * 30),
  },
};

I have checked the example code extensively, as well as other sources online (1, 2, 3 and even more), and I'm still struggling to make sense why this happens.

The app is hosted on Azure as a Static Web App, and unfortunately I can't trace Server Action logs remotely (prod, stg) - initially I thought it could be related to caching but I'm not sure anymore since I already added revalidatePath? I'm relatively new to auth and cookie management (and Next Server Actions for that matter), so I don't know if the fault is on Next, iron-session or even some Azure Static Web App config. I just have the impression that this code should work, as it's quite similar to the working example.

Thanks for any help in advance!

Below the results of the POST request from the Server Action, when it doesn't work:
Image
Image
Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions