Search code examples
reactjsnext.jsnext-authreact-server-components

NextAuth React Server Components Dynamic server usage Error


Been trying to use react server components, however, I'm stuck at retrieving session data from next auth. The recommended way to do this is getServerSession which throws an error:

Error: Dynamic server usage: force-dynamic

As per docs, I've set dynamic option to force-dynamic, however, the error persists regardless of the value. Interestingly enough, the page loads fine when refreshed on the "server component" route, however, when navigating to it from a different page, it throws an error

import {authOptions} from 'path/to/[...nextauth]'
export const dynamic = 'force-dynamic'
export default async function Page() {
  const session = await getServerSession(authOptions);
  return null;

UPDATE:

If dynamic is left with default value, the error message changes to:

Error: Dynamic server usage: headers

  14 | export default async function Page(...props: any) {
> 15 | const session = await getServerSession(authOptions);
     |                                       ^
  16 | return null;

the behaviour stays the same, meaning it loads fine when on the rsc route, but throws error when navigating to it


Solution

  • So, as it turns out, the issue was 'caused by another server component which sets up my next-intl and uses the generateStaticParams function. Once I set it to undefined it worked fine.

    
    function getStaticParams(){...}
    
    export const generateStaticParams = process.env.NODE_ENV === 'production' ? getStaticParams : undefined