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
- Cookie Detection:
- On server: Uses H3's
getCookieanduseRequestEvent()to read cookies from the request. - On client: Parses
document.cookieto fetch values.
- On server: Uses H3's
- Store Syncing:
- Populates
debugPanelanddebugPanelOpenin the root Pinia store.
- Populates
- Runtime Config Sync:
- Updates the public runtime config (
appDebug) for universal availability.
- Updates the public runtime config (
๐ง 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).