#next.js api from client component
1 messages · Page 1 of 1 (latest)
Hi @runic horizon. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Next.js, you cannot directly access HTTP request headers (such as session tokens) from a Client Component. The browser environment does not expose incoming request headers to client-side JavaScript for security reasons.
If you need to attach a session token to an API request from a Client Component, you typically have two options:
-
Use Cookies:
If your session token is stored in a cookie (especially an HTTP-only cookie), the browser will automatically send it with every request to your API endpoint, as long as the request is made to the same origin and with the correct credentials policy (e.g.,credentials: 'include'). You do not need to manually read or attach the cookie in your client code.Example using
fetchin a Client Component:// 'use client' useEffect(() => { fetch('/api/your-endpoint', { credentials: 'include', // ensures cookies are sent }) .then(res => res.json()) .then(data => { // handle data }); }, []); -
Expose the Token via a Client-Safe Mechanism:
If you need to access a token that is not in a cookie, you must first make it available to the client in a safe way (e.g., via a custom API route that reads the token server-side and returns it, or by passing it as a prop from a Server Component). However, be cautious: exposing sensitive tokens to the client can introduce security risks.
Important:
- The
headersandcookiesfunctions fromnext/headersare only available in Server Components and API Route Handlers, not in Client Components. Attempting to use them in a Client Component will result in an error How to migrate from Pages to the App Router > Accessing Request Object. - If you need to read a value from a cookie in a Client Component (and it's not HTTP-only), you can use the standard browser APIs like
document.cookie, but this is not recommended for sensitive data.
Summary:
- You cannot read incoming request headers directly in a Client Component.
- Use cookies for session tokens, and let the browser handle sending them.
- For other tokens, securely expose them to the client if absolutely necessary, but be aware of the security implications.