VENNStart
Project / Ajuma Garden

Why caching the menu hid my Next.js shop’s admin buttons

Public navigation and admin permissions shared one response. I cached its anonymous version on Ajuma Garden, and the shop owner lost the admin buttons too.

Lê Anh Tuấn4 min readView live site ↗
Ajuma Garden

The shop owner was logged in and the header still had no admin buttons. No failed requests, a clean console. The shop is Ajuma Garden (fruit, vegetables, flowers), which I moved from Create React App to the Next.js 15 App Router, and the cause was a menu cache I'd added: public navigation and the admin flags came back in one response, and I'd cached only the logged-out version.

The existing backend has one endpoint that returns everything the layout needs: menu, header, footer, banners, config. For a logged-in user it also includes UserInfo and an Admin object with flags like ShowBtnAdmin and ShowBtnRefreshCache. The header reads those flags to show the admin and cache refresh buttons.

In the CRA version, axios called the API from the browser with the user's Authorization header, so each person got their own response. With the App Router, the layout fetches on the server and passes initialMenuData to a client component that dispatches it into the old Redux store.

A cache without a token stores only the anonymous copy

The menu is on every page and almost never changes, so I wrapped the call in unstable_cache:

// (root)/layout.tsx, old version
const getCachedMenuData = unstable_cache(
  async () => {
    const menuResp = await seoServices.getMenuPage();
    return menuResp?.Data;
  },
  ['menu-data'],
  { tags: ['menu-data'], revalidate: 1800 }
);

const Root = async ({ children }) => {
  const initialMenuData = await getCachedMenuData();
  return <Wrapper initialMenuData={initialMenuData}>{children}</Wrapper>;
};

The cached function has a fixed key, takes no arguments and doesn't send a token. So the API always answered as an anonymous visitor, with no Admin object, and everyone got that copy. For admins, adminButtons was null, the header hid the buttons, and the admin page didn't find ShowBtnAdmin, so it sent the owner back to the home page.

The legacy auth code kept the token in localStorage, which a Server Component can't read. Since I'd added a middleware guard for /account-*, login also wrote the token to an AUTH_ACCESS_TOKEN_KEY cookie. The menu call never read it.

The fix is a server helper that reads the cookie, plus a branch in each layout:

// helpers/SSRToken.ts, trimmed
'use server';
import { cookies } from 'next/headers';

export async function getSSRToken(): Promise<string | null> {
  try {
    const cookieStore = await cookies();
    return cookieStore.get('AUTH_ACCESS_TOKEN_KEY')?.value || null;
  } catch {
    return null;
  }
}

// (root)/layout.tsx and (seo)/layout.tsx
const token = await getSSRToken();
const initialMenuData = token
  ? await seoServices.getMenuPage(token) // per-user, includes Admin
  : await getCachedMenuData();           // shared anonymous copy

The token also goes into the data for the home, slug and category pages. The server calls there run as the same user as the layout.

The home page was set to force-static. I checked the Next.js 15.1 source: on a force-static route, cookies() returns an empty object, so the token was always missing. I switched it to force-dynamic. The route configuration docs describe force-dynamic as no-store on every fetch, but in the 15.1 source that only applies to fetches without a cache option of their own, and the service layer sets force-cache with revalidate: 3600. For per-request rendering with a cached public part, keep dynamic = 'auto', read cookies(), and opt the public reads into caching yourself.

A force-dynamic route isn't ISR anymore either. The slug page still exports revalidate = 1800, but it renders on every request.

Login has to reload the page

The login form called HAuth.login(response, props), but login() takes one argument, so the afterLogin callback that reloads the page never ran. The server never rendered again, and the layout kept the anonymous menu.

// common_login.tsx
successCallBack: (response: any) => {
  HAuth.login(response);   // sets localStorage + cookie
  props?.afterLogin?.();   // shop login passes () => window.location.reload()
},

After the reload, the request includes the cookie and the layout takes the token branch.

The admin page used to call redirect('/') inside the render of a client class component. Now it waits in componentDidMount and componentDidUpdate until isLoadedGetMenuPage is true, and only then sends the user home if ShowBtnAdmin isn't true. Before the menu arrives, a missing admin flag doesn't mean the user isn't an admin.

The cart stays on the client

Cart items live in Redux and localStorage, with no shared cache in the path. The server is only called on layout mount to refresh prices, and that hook needs a ref to avoid looping:

// TheLayout.tsx
const prevCartIdsRef = React.useRef<string>('');

useEffect(() => {
  if (isRenderSsr) return;
  const currentIds = getCurrentCartIds(); // "id1,id2,..."
  if (currentIds && currentIds !== prevCartIdsRef.current) {
    prevCartIdsRef.current = currentIds;
    requestUpdateCart();
  }
}, [isRenderSsr, cartProducts, getCurrentCartIds, requestUpdateCart]);

requestUpdateCart dispatches a new cartProducts array. Without the ref, the effect runs again and calls the API forever.

The real fix needs a backend change

The root problem is one response mixing public data with per-user flags. Moving Admin and UserInfo to a separate call would let the menu be cached for everyone, but that needs a backend change. The token branch is a frontend workaround, and any per-user flag added to that response later depends on each layout remembering to branch.

The service layer still requests force-cache with a one-hour revalidation for token-bearing calls. force-dynamic doesn't override an explicit option like that, and the responses stay in the Data Cache. The Authorization header separates cache entries by token, but a permission change can leave a cached response stale for up to an hour. I'd set cache: 'no-store' on per-user calls rather than depend on the route config.

The tag names have drifted too. Since the fix, both layouts use the shared getCachedMenuData from lib/menuCache.ts, tagged seo-menu-data and header-data, while the footer editor and the revalidate route still use menu-data, the tag of the old inline cache. The repo already has a REVALIDATE_TAGS constant to take names from.

The slug page still calls redirect() inside a try. redirect() works by throwing, so the catch swallows it and the page keeps rendering. Move the call out of the try, or call unstable_rethrow(error) on the first line of the catch.

  • Next.js
  • E-commerce
  • Caching
  • App Router
  • Redux
  • Client project

I'm Tuấn (Venn), a web developer in Ho Chi Minh City. I mostly build Next.js sites and web apps, and I take freelance work.

Work with me

More posts

  1. 01Guide4 min read

    Deploying Next.js and NestJS to AWS EC2 with Docker Compose

    How I deploy a pnpm monorepo to one EC2 box. Images get built in GitHub Actions and Docker Compose pulls them from GHCR. The server has no code.

  2. 02Guide4 min read

    How I store OAuth tokens for social media APIs in NestJS

    OAuth for Facebook, TikTok and YouTube in a NestJS API. State and PKCE, encrypted tokens, refreshing before each publish, and when to ask for a reconnect.

  3. 03vennee.dev3 min read

    llms.txt on my Next.js site, and now Lighthouse grades it

    vennee.dev has a hand-written llms.txt and an llms-full.txt built from the blog. Notes on the spec, .txt routes in Next.js, and Lighthouse 13's new audit.