Next.js Discord

Discord Forum

async context: `dynamic-server-error`

Unanswered
Paul posted this in #help-forum
Open in Discord
Hello, when I build I run into a bunch of these errors: https://nextjs.org/docs/messages/dynamic-server-error

I'm trying to track down why this is caused, I do indeed call headers in the following example code in my root layout:

 const [
      hierarchyConfig,
      selectedLocation,
    ] = await Promise.all([
      benchmarkPromise(
        retrieveCachedHierarchyConfig(token),
        "retrieveCachedHierarchyConfig",
        "layout",
      ),
      benchmarkPromise(
        getSelectedHierarchy(token),
        "getSelectedHierarchy",
        "layout",
      ),


each of those function retrieveCachedHierarchyConfig and getSelectedHierarchy use headers but it's awaited at the top level.

the benchmarkPromiseis a simple perf debugger:
export function benchmarkPromise<T>(
  promise: Promise<T>,
  label: string,
  namespace?: string,
): Promise<T> {
  const dbg = Debug(createNamespace(namespace));
  const start = performance.now();
  return promise
    .then((res) => {
      const duration = performance.now() - start;
      dbg("%s resolved in %dms", label, duration.toFixed(2));
      return res;
    })
    .catch((err) => {
      const duration = performance.now() - start;
      dbg("%s rejected in %dms", label, duration.toFixed(2));
      throw err;
    });
}


Do you see any obvious reason why I would get these issues? I suspect it might be related to one of the following:
- using a Promise.all
- calling headers conditionally, eg:
  async function retrieveCachedHierarchyConfig(pathname?:string){
     let currentPathname = pathname
     if(!currentPathname){
       const headersStore = await headers()
       currentPathName = headersStore.get("x-pathname")
     }
  }
  


But i'm not 100% sure. Is there also a way to debug these cases in development?

3 Replies

I'm wondering if I should just set the following explicitly add the dynamic directive to mark it as dynamic:
const dynamic = 'force-dynamic'
I also see that a try{}catch{} might cause the issue: https://discord.com/channels/752553802359505017/1369573260169314324
I will try and create a minimal reproduction to better debug the issue