Logout route not clearing client router cache
Answered
Flammulated Owl posted this in #help-forum
Flammulated OwlOP
I have a logout route with this:
When I link to this route the cookie gets deleted correctly and the redirect happens, but the client router cache doesn't clear itself. The issue is that if after I logout I go to the previous page hitting back on the browser, I see the authenticated page even if I shouldn't. In the network tab no requests are made to the secured endpoint, it just uses what's in the cache.
Any ideas? Thanks.
export async function GET() {
const { session } = await validateRequest();
if (session) {
await lucia.invalidateSession(session.id);
const sessionCookie = lucia.createBlankSessionCookie();
cookies().set(sessionCookie.name, sessionCookie.value, sessionCookie.attributes);
}
revalidatePath("/", "layout");
redirect("/");
}When I link to this route the cookie gets deleted correctly and the redirect happens, but the client router cache doesn't clear itself. The issue is that if after I logout I go to the previous page hitting back on the browser, I see the authenticated page even if I shouldn't. In the network tab no requests are made to the secured endpoint, it just uses what's in the cache.
Any ideas? Thanks.
Answered by joulev
Server actions can clear the router cache but route handlers cannot
4 Replies
Flammulated OwlOP
I should mention I'm on next 14.2.2
Server actions can clear the router cache but route handlers cannot
Answer
@joulev Do this in a server action instead of a route handler
Flammulated OwlOP
ok thanks, I assumed that since the handler was replying with the correct
I'm adding a success page after the logout like this and redirecting to it in
so that I can keep a route instead of a server action.
Vary headers then the router should have been able to respect the clearing of the cache.I'm adding a success page after the logout like this and redirecting to it in
logout:"use client";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
export default function Page({}: {}) {
const router = useRouter();
useEffect(() => {
router.refresh();
router.replace("/");
}, []);
return <></>;
}so that I can keep a route instead of a server action.