next.js: Runtime Edge throws an "Invariant: Method expects to have requestAsyncStorage, none available"

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
      Platform: win32
      Arch: x64
      Version: Windows 10 Pro
    Binaries:
      Node: 18.16.0
      npm: N/A
      Yarn: N/A
      pnpm: N/A
    Relevant Packages:
      next: 13.4.8
      eslint-config-next: 13.4.8
      react: 18.2.0
      react-dom: 18.2.0
      typescript: 5.1.6
    Next.js Config:
      output: N/A

Which area(s) of Next.js are affected? (leave empty if unsure)

App directory (appDir: true), Metadata (metadata, generateMetadata, next/head, head.js), Middleware / Edge (API routes, runtime)

Link to the code that reproduces this issue or a replay of the bug

https://github.com/NastykSwED/next-edge-invariant-error

To Reproduce

  1. pnpm install

  2. pnpm dev

  3. Go to localhost:3000

  4. Look at terminal, see error:

error Error: Invariant: Method expects to have requestAsyncStorage, none available
    at RootLayout (./src/app/layout.tsx:23:71)
    at stringify (<anonymous>)
digest: "3964514174"

Describe the Bug

When using the runtime edge, if we use the headers() functions from “import { headers } from 'next/headers'”, this error occurs, not only in layout.tsx | jsx files but also in page.tsx | jsx files and in generateMetadata functions. The error does not occur in older versions such as next@13.4.7: layout.tsx file Screenshot_1

page.tsx file Screenshot_2

generateMetadata function Screenshot_3

Expected Behavior

It would be expected that when using the runtime edge this error would not occur. In earlier versions such as next@13.4.7 it works correctly.

Which browser are you using? (if relevant)

Microsoft Edge 114.0.1823.67

How are you deploying your application? (if relevant)

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Reactions: 31
  • Comments: 42 (6 by maintainers)

Most upvoted comments

I’m also facing this issue. But more specificly.

The error only occured on dynamic route (app router).

Example:

Works perfectly:

// apps/dashboard/page.tsx

export default async function Dashboard() {
  const data = await api.myApiRoute.myProcedure();
  return <>Dashpage</>
}

On dynamic route, it throws the error Error: Invariant: headers() expects to have requestAsyncStorage, none available.

// apps/dashboard/posts/[postId]/page.tsx

type Props = {
  readonly params: {
    readonly postId: string;
  }
}

export default async function PostDetail({params: { postId }}: Props) {
  const data = await api.myApiRoute.myProcedure();
  return <>PostDetail page {postId}</>
}

the api is a simple trpc caller:

import "server-only";

import { headers } from "next/headers";
import { appRouter } from "~/server/api/root";
import { db } from "~/server/db";
import { auth } from "@clerk/nextjs";

export const api = appRouter.createCaller({
  db,
  headers: headers(), // here the error is throw
  auth: auth(),
});

there is my next info output:

Operating System:
  Platform: linux
  Arch: x64
  Version: #1 SMP Thu Oct 5 21:02:42 UTC 2023
Binaries:
  Node: 21.2.0
  npm: 10.2.3
  Yarn: N/A
  pnpm: 8.9.0
Relevant Packages:
  next: 13.5.6
  eslint-config-next: 13.5.6
  react: 18.2.0
  react-dom: 18.2.0
  typescript: 5.3.2
Next.js Config:
  output: N/A

I’m working with clerk for the auth part.

What I found until now:

The return new maybeGlobalAsyncLocalStorage(); seems different regarding a request where it’s ok. the value of the return:

AsyncLocalStorage {
  kResourceStore: Symbol(kResourceStore),
  enabled: false,
  _onPropagate: null
}

comparing to an ok:

AsyncLocalStorage {
  kResourceStore: Symbol(kResourceStore),
  enabled: true,
  _onPropagate: null
}

so it seems that the AsyncLocalStorage is disabled I was going deeper when I found out this type definition (from node):

        /**
         * Returns the current store.
         * If called outside of an asynchronous context initialized by
         * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it
         * returns `undefined`.
         * @since v13.10.0, v12.17.0
         */
        getStore(): T | undefined;

I prepared a little repository to replicate the issue: https://github.com/joachimjusth/nextjs-issue-52176

I hope it’ll help

Having the same issue. using cookies for supabase on server side api to receive a webhook.

import { cookies } from ‘next/headers’ import { createServerComponentClient } from ‘@supabase/auth-helpers-nextjs

const supabase = createServerComponentClient({ cookies })

Getting this error when deployed on vercel Error: Invariant: Method expects to have requestAsyncStorage, none available

I had this issue trying to run Clerk Auth on edge on the newest version (13.4.9). It seems to be only in windows environments. I tested the repo in WSL2 and I stopped getting the error. Windows will only work up til 13.4.7.

This is more a platform related issue. So the localhost at windows machine was having this issue. I was able to resolve it by adding this line in app/page.js file

export const runtime = ‘nodejs’;

“next”: “13.5.5-canary.14”,also solves the problem

I’m getting this same issue now even on 13.4.7, but only when deployed. It works fine locally.

@azeemasim01 Yeah, but that’s exactly the issue, runtime edge on windows causes the bug. I am using the edge runtime, so switching to nodejs is not a solution for me or anyone committed to edge.

Error still persists on version 13.5.2. I’m on windows and have tried running it normally and using WSL.

The issue was solved through this way: https://github.com/vercel/next.js/issues/45371#issuecomment-1655408690

The issue:

In prod, Next.js throws that error message: Invariant: Method expects to have requestAsyncStorage, none available. This error message occurs only server components and also in prod (Deploy on Cloudflare). No issue in local.

When it throws the error:

When it was fetching data from Supabase database in the server components in prod, not local.

Dependencies:

"@supabase/auth-helpers-nextjs": "^0.7.3",
"@supabase/supabase-js": "^2.31.0",
"next": "13.4.12",

next-info:

    Operating System:
      Platform: linux
      Arch: x64
      Version: #50-Ubuntu SMP PREEMPT_DYNAMIC Mon Jul 10 18:24:29 UTC 2023
    Binaries:
      Node: 18.16.0
      npm: 9.5.1
      Yarn: 1.22.19
      pnpm: 8.6.7
    Relevant packages:
      next: 13.3.0
      eslint-config-next: N/A
      react: 18.2.0
      react-dom: 18.2.0

Dashboard component:

import { createServerSupabaseClient, getSession } from "@/components/supabase/supabase-server";

export default async function Dashboard() {
    const supabase = createServerSupabaseClient() // this line works well.
    const serverSession = await getSession() // this line works well.
    const userInfo = serverSession?.user

    const pending = await supabase
        .from('table')
        .select('*', { count: 'exact', head: true })
        .eq('username', userInfo.user_metadata.username)
        .eq('status', 0)

    // Here's the error:
    console.log("ERROR [PENDING] DETAILS: ", JSON.stringify(pending, null, 2))
}

supabase-server.js:

import { cookies } from 'next/headers';
import { cache } from 'react';
import { createServerComponentClient } from '@supabase/auth-helpers-nextjs';

export const createServerSupabaseClient = cache(() =>
    createServerComponentClient({ cookies })
)

export async function getSession() {
    const supabase = createServerSupabaseClient()
    try {
        const {
            data: { session }
        } = await supabase.auth.getSession()
        return session
    } catch (error) {
        console.error('Error:', error)
        return null
    }
}

middleware.js:

import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs'
import { NextResponse } from 'next/server'

export async function middleware(req) {
    const res = NextResponse.next()
    const supabase = createMiddlewareClient({ req, res })
    await supabase.auth.getSession()
    return res
}

Additional:

I guess the problem comes from the next/headers package. But why is it working in local? Everything is perfect in the client components, also in local. I don’t want to do prop drilling.

A comment about this issue from GitHub: https://github.com/vercel/next.js/issues/45371#issuecomment-1652192961

  • Used server-only package
  • Removed the cache() from react
  • Run createServerComponentClient directly in the Dashboard component, not imported

I have the exact same issue with Next 14.0.4 where a catch all route that only returns a “NotFound” page causes the issue… The application is completely server side renderen (except a few client side components). The issue only happen when I try to access draftMode which is related to headers as discussed here.

I am still looking for a workaround because it is annoying because I use a headless CMS and this is the entry point for editors to see their changes that are not approved an published yet

Tried Next 13.5.3 with Node 18 on Windows 11, still no luck for me. Latest version that works is 13.4.7

The error still occurs in version 13.4.13

We cannot recreate the issue with the provided information. Please add a reproduction in order for us to be able to investigate.

Why was this issue marked with the please add a complete reproduction label?

To be able to investigate, we need access to a reproduction to identify what triggered the issue. We prefer a link to a public GitHub repository (template for pages, template for App Router), but you can also use these templates: CodeSandbox: pages or CodeSandbox: App Router.

To make sure the issue is resolved as quickly as possible, please make sure that the reproduction is as minimal as possible. This means that you should remove unnecessary code, files, and dependencies that do not contribute to the issue.

Please test your reproduction against the latest version of Next.js (next@canary) to make sure your issue has not already been fixed.

I added a link, why was it still marked?

Ensure the link is pointing to a codebase that is accessible (e.g. not a private repository). “example.com”, “n/a”, “will add later”, etc. are not acceptable links – we need to see a public codebase. See the above section for accepted links.

What happens if I don’t provide a sufficient minimal reproduction?

Issues with the please add a complete reproduction label that receives no meaningful activity (e.g. new comments with a reproduction link) are automatically closed and locked after 30 days.

If your issue has not been resolved in that time and it has been closed/locked, please open a new issue with the required reproduction.

I did not open this issue, but it is relevant to me, what can I do to help?

Anyone experiencing the same issue is welcome to provide a minimal reproduction following the above steps. Furthermore, you can upvote the issue using the 👍 reaction on the topmost comment (please do not comment “I have the same issue” without reproduction steps). Then, we can sort issues by votes to prioritize.

I think my reproduction is good enough, why aren’t you looking into it quicker?

We look into every Next.js issue and constantly monitor open issues for new comments.

However, sometimes we might miss one or two due to the popularity/high traffic of the repository. We apologize, and kindly ask you to refrain from tagging core maintainers, as that will usually not result in increased priority.

Upvoting issues to show your interest will help us prioritize and address them as quickly as possible. That said, every issue is important to us, and if an issue gets closed by accident, we encourage you to open a new one linking to the old issue and we will look into it.

Useful Resources

@HotCustard do you have a reproduction? I tried running the one in the description, but I could not reproduce this. 🤔