Nuxt & Universal SSR (50 Qs)•Part 2: Core Architecture & Data Fetching (Mid-Level)
How does `useCookie()` work across SSR and client?
senior LevelCode ExampleCLISSR & HydrationSystem Design
In Simple Words:
useCookie(name, options) provides an SSR-friendly, reactive ref for reading and writing cookies.
- On the Server: It reads incoming cookies from request headers (
event.node.req.headers.cookie) and queuesSet-Cookieresponse headers when changed. - On the Client: It reads and mutates
document.cookie. Because it is reactive, updatingauthCookie.value = 'new_token'synchronizes state immediately.
typescript
// composables/useAuth.ts
export const useAuthCookie = () => {
const token = useCookie<string | null>('token', {
maxAge: 60 * 60 * 24 * 7, // 7 days
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
httpOnly: false // Accessible to JS
});
return token;
};