Middlewares

Cookie Check

๐Ÿงญ Overview

The cookie-check.ts middleware reads two cookiesโ€”debugPanel and debugPanelOpenโ€”and stores their values in the Pinia root store. It makes these values available both server-side and client-side, enabling dynamic debugging UI toggles.

This middleware is global, meaning it runs on every route.


๐Ÿ“„ Code Example

// middleware/cookie-check.global.ts
import { getCookie } from "h3";

export default defineNuxtRouteMiddleware((to, from) => {
  let debugPanel: string | undefined = "false";
  let debugPanelOpen: string | undefined = "false";
  const rootStore = useRootStore();

  if (process.server) {
    const event = useRequestEvent();
    debugPanel = getCookie(event, "debugPanel");
    debugPanelOpen = getCookie(event, "debugPanelOpen");
  } else if (process.client) {
    debugPanel = document.cookie
      .split("; ")
      .find((row) => row.startsWith("debugPanel="))
      ?.split("=")[1];
    debugPanelOpen = document.cookie
      .split("; ")
      .find((row) => row.startsWith("debugPanelOpen="))
      ?.split("=")[1];
  }

  if (debugPanel === undefined) debugPanel = "false";
  if (debugPanelOpen === undefined) debugPanelOpen = "false";

  rootStore.debugPanel = JSON.parse(debugPanel);
  rootStore.debugPanelOpen = JSON.parse(debugPanelOpen);

  const runtimeConfig = useRuntimeConfig();
  runtimeConfig.public.appDebug = rootStore.debugPanel;
});

โš™๏ธ How It Works

  1. Cookie Detection:
    • On server: Uses H3's getCookie and useRequestEvent() to read cookies from the request.
    • On client: Parses document.cookie to fetch values.
  2. Store Syncing:
    • Populates debugPanel and debugPanelOpen in the root Pinia store.
  3. Runtime Config Sync:
    • Updates the public runtime config (appDebug) for universal availability.

๐Ÿ”ง Use Case

Used to toggle UI panels (like a debug inspector or dev tools) conditionally based on cookies.

This middleware would run globally via filename convention: cookie-check.global.ts.


๐Ÿ“ Notes

  • This middleware doesn't block or redirect.
  • Helps sync cookie state to Pinia for global reactivity.
  • Avoids hydration mismatch by parsing cookies only on correct runtime (client/server).

๐Ÿ“š Learn More


Copyright ยฉ 2026