Search code examples
node.jsnext.jsnext-auth

How to sign out using the POST /api/auth/signout endpoint with Next Auth?


This Reddit post suggests to make "an api call in signOut event. The backend handled the rest of it."

Sure, so let's write it :

await fetch('/api/auth/signout', { method: "POST" });

Except the request is redirected through a 302 to GET /api/auth/signout?csrf=true which, in turn, redirects to GET /auth/sign-out, my custom sign out page; the user is not signed out.

The documentation does specify that the "POST submission requires CSRF token from /api/auth/csrf", however there is no example usage of this.

Hitting /api/auth/csrf I get a JSON response, so I simply used that value as the body of the initial POST request:

await fetch('/api/auth/signout', {
  method: "POST",
  body: await fetch('/api/auth/csrf').then(rs => rs.text())
});

Which does make a request, then adds a payload of {"csrfToken":...}, but the same redirects, and the user is still not signed out.

My goal is to sign-out and not be redirected when calling the initial POST request. Is that possible?


Solution

  • I was close. This is the request that ended up working :

    await fetch('/api/auth/signout?callbackUrl=/api/auth/session', {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      }
      body: await fetch('/api/auth/csrf').then(rs => rs.text())
    });
    

    The callback only serves to not be redirected to the sign in page, the default behavior.

    The Content-type is JSON even if the body is a string; this tells Next.js how to parse the content of the body.