awinogrodzki / next-firebase-auth-edge

Next.js Firebase Authentication for Edge and Node.js runtimes. Compatible with latest Next.js features.
https://next-firebase-auth-edge-docs.vercel.app/
MIT License
404 stars 39 forks source link

Logout user from inside middleware `handleValidToken` #196

Closed steve-marmalade closed 1 day ago

steve-marmalade commented 1 month ago

Hey there, is there an idiomatic way to support the following case:

awinogrodzki commented 1 month ago

Hello 👋

My suspicion is that I can do this by deleting the authentication cookies that are set by this library, and then redirecting

As long as you redirect user by returning NextResponse.redirect from the middleware this approach should work fine.

In 1.6.0-canary.2 you can use removeCookie function imported from next-firebase-auth-edge/lib/next/cookies

This function is also called when logging out user with /api/logout endpoint.

It looks as follows:

export function removeCookie(
  response: NextResponse,
  options: RemoveAuthCookiesOptions
) {
  const {maxAge, expires, ...cookieOptions} = options.cookieSerializeOptions;

  response.headers.append(
    'Set-Cookie',
    serialize(options.cookieName, '', {
      ...cookieOptions,
      expires: new Date(0)
    })
  );
}

As a part of handleValidToken function, you can return redirect response similar to this:

const response = NextResponse.redirect(...);

removeCookie(response, { cookieName: 'AuthToken', cookieSerializeOptions: {...} });

return response;

Cheers 🎉

awinogrodzki commented 12 hours ago

Hey @steve-marmalade!

Just letting you know that since next-firebase-auth-edge@1.6.1, removeCookie method has been renamed to removeCookies to better reflect the behaviour. Sorry for the inconvenience.

You can also checkout enableMultipleCookies option added to authMiddleware

See https://github.com/awinogrodzki/next-firebase-auth-edge?tab=readme-ov-file#whats-new-in-v16 for a summary of new features.

Cheers 🎉