#can we get cookies, request, response in client component?

1 messages · Page 1 of 1 (latest)

tame widgetBOT
#

Hi @mortal charm. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

No, you cannot directly access cookies, request, or response in a client component in Next.js. Client components are pre-rendered to HTML during next build and Web APIs like window, localStorage, and navigator are not available on the server. Therefore, you need to safely access these APIs only when running in the browser.

Here is an example of how you can safely access these APIs in a client component:

'use client';
 
import { useEffect } from 'react';
 
export default function ClientComponent() {
 useEffect(() => {
 // You now have access to `window`
 console.log(window.innerHeight);
 }, [])
 
 return ...;
}

(Source: Next.js Documentation (https://nextjs.org/docs/app/building-your-application/deploying/static-exports#browser-apis))

However, you can access cookies and headers in server components or middleware in Next.js. For example:

import { cookies } from 'next/headers';
 
export default function Page() {
  const cookieStore = cookies();
  const theme = cookieStore.get('theme');
  return '...';
}

import { headers } from 'next/headers';
 
export default function Page() {
  const headersList = headers();
  const referer = headersList.get('referer');
 
  return <div>Referer: {referer}</div>;
}

(Source: Github Issue (https://github.com/vercel/next.js/issues/48092))

Please note that the above code is for server components and not for client components.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: