Next.js Discord

Discord Forum

next/headers in utility function shared by RSCs

Unanswered
House Wren posted this in #help-forum
Open in Discord
House WrenOP
is there a way to "flag" a function as a function that can only run in server components?

for example:

import 'server-only';

import { cookies } from 'next/headers';

export function getSessionToken(): string | undefined {
  return cookies().get('auth_token')?.value;
}


that throws an error:

You're importing a component that needs next/headers. That only works in a Server Component but one of its parents is marked with "use client", so it's a Client Component.

context: getSessionToken in reality is a little more complex that the example, I don't want to have to repeat that code in every RSC that needs it. And as you can see I already tried with 'server-only', but that didn't work 😦

6 Replies

European sprat
probably need to see the bigger picture of your code and how it's implemented since what you've shared doesn't give enough details to see why that error is appearing
House WrenOP
well, it's a more generic question of how I can share a function between different RSCs if that function access next/headers

the error message is missleading, I'm accessing getSessionToken from a react server component, not a client one, but it looks like NextJS can't tell
European sprat
are you exporting it from a file that also has exports used by a client component?
i have a "server-only" file which exports my auth function which uses headers() and i use that auth function in RSC and routes without a problem
House WrenOP
I don't, but I'm starting to think that a RSC cannot be rendered inside a client component?

I do have a 'use client' in the component that wraps the RSC that uses this function:

'use client'

export const ProductCard = (...) => {
  return (
    <Dialog>
    <...>
    <...>
      <DialogContent>
        <ProductDetails productId={productId} /> // <--- server component that uses the function that uses next/headers
      </DialogContent>
    </Dialog>
  );
};