最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Next.js, NextAuth, and Chrome: Protected content flashes after logout despite Cache-Control - Stack Overflow

programmeradmin3浏览0评论

I'm developing a Next.js application using NextAuth.js for authentication, and I'm facing a persistent issue:

After logging out, Chrome still shows protected content for a fraction of a second when navigating between pages.

This doesn't happen on Brave, only on Chrome.

Technical Setup

  • Framework: Next.js
  • Authentication: NextAuth.js (using getToken() and middleware)
  • Problematic Browser: Google Chrome (works fine on Brave)
  • Auth mechanism: JWT session with next-auth.session-token
  • Middleware used for cache control

Problem Description After logging out, when I navigate through pages, Chrome momentarily flashes protected content.

  • The session is correctly terminated.
  • The middleware correctly redirects to /login.
  • The issue does not occur on Brave.
  • On Chrome, protected pages are briefly visible before the redirect happens.

Steps Taken So Far Cache-Control headers in the middleware:

response.headers.set('Cache-Control', 'no-cache, no-store, must-revalidate, proxy-revalidate, private, max-age=0');
response.headers.set('Pragma', 'no-cache');
response.headers.set('Expires', '0');
response.headers.set('Surrogate-Control', 'no-store');
response.headers.set('Vary', 'Authorization, Cookie');

Forced a hard reload after logout: window.location.href = '/login?cacheBust=' + Date.now();

⚠️ Disabled Next.js prefetching:

Go to My Orders

Browser & cache attempts:

  • Disabled Chrome bfcache from chrome://flags/#back-forward-cache.

  • Disabled cache via Chrome DevTools → Network → Disable Cache.

  • Cleared Service Worker caches with the following code:

    if ('caches' in window) { caches.keys().then((names) => { for (let name of names) caches.delete(name); }); }

Despite all these attempts, the issue persists.

Current Middleware Configuration

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getToken } from 'next-auth/jwt';
import Logger from '@/utils/logger';

export async function middleware(req: NextRequest) {
    const { pathname } = req.nextUrl;

    // Exclude /api/auth to avoid infinite loops
    if (pathname.startsWith('/api/auth')) return NextResponse.next();

    // Get the token
    let token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });

    // Redirect if token is missing
    if (!token) {
        Logger.warn('

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论