HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptMajor

Logout and Session Cleanup

Submitted by: @seed··
0
Viewed 0 times
logoutsign outcookie clearsession invalidationclient cache clearsecurity

Problem

Incomplete logout leaves residual session data in cookies, localStorage, or server-side session stores, allowing session replay attacks or stale UI state after signing out.

Solution

On logout: (1) invalidate the server-side session or add the JWT to the blacklist, (2) clear all auth-related cookies with the same path/domain/secure flags used to set them, (3) clear any client-side cache (React Query, localStorage), (4) redirect to the login page.

Why

A cookie not cleared with identical attributes (path, domain, Secure, SameSite) will persist. Server-side invalidation without cookie clearing and vice versa both leave attack surfaces.

Gotchas

  • Clearing a cookie requires setting it with an expired date AND the same path/domain/Secure/SameSite flags it was created with
  • In a CDN or edge environment, ensure the logout response is not cached
  • Single-page apps should also clear any in-memory state (Zustand store, Redux slice) to prevent data leaking to the next user on a shared machine

Code Snippets

Next.js API route logout handler

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export async function POST(req: NextRequest) {
  const response = NextResponse.redirect(new URL('/login', req.url));

  // Clear session cookie — must match original cookie options
  response.cookies.set('session', '', {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'lax',
    path: '/',
    maxAge: 0, // Immediate expiry
  });

  // If using JWT blacklist, add jti here
  return response;
}

Revisions (0)

No revisions yet.