Removing Credentials
The next-firebase-auth-edge
library provides a removeCookies
method to remove authenticated cookies within Middleware. This is useful for situations where you want to explicitly log a user out of the app.
Removing Credentials in Middleware or API routes
To remove authenticated cookies in Middleware or API routes, use the removeCookies
function from next-firebase-auth-edge/lib/next/cookies
. This will attach expired Set-Cookie
headers to the response, prompting the browser to delete the authenticated cookies.
import {NextRequest, NextResponse} from 'next/server';
import {removeCookies} from 'next-firebase-auth-edge/lib/next/cookies';
//...
function forceLogout(request: NextRequest) {
const response = NextResponse.redirect(new URL('/login', request.url));
removeCookies(request.headers, response, {
cookieName: 'AuthToken',
cookieSerializeOptions: {
path: '/',
httpOnly: true,
secure: false,
sameSite: 'lax' as const,
maxAge: 12 * 60 * 60 * 24
}
});
return response;
}
Removing Credentials in Server Actions
To remove authenticated cookies in Server Actions, use the removeServerCookies
function from next-firebase-auth-edge/lib/next/cookies
. This will remove authentication cookies using cookies.delete
method on Next.js cookies object
import {NextRequest, NextResponse} from 'next/server';
import {cookies} from 'next/headers';
import {removeServerCookies} from 'next-firebase-auth-edge/lib/next/cookies';
// Since Next.js 15, `cookies` and `headers` functions returns a Promise, so we need to precede them with `await`.
removeServerCookies(await cookies(), {
cookieName: 'AuthToken',
});