next.js: NextJS 14.2.4 With-Supabase Build Error - Error: `cookies` was called outside a request scope.

Verify canary release

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

Provide environment information

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 23.5.0: Wed May  1 20:12:58 PDT 2024; root:xnu-10063.121.3~5/RELEASE_ARM64_T6000
  Available memory (MB): 16384
  Available CPU cores: 10
Binaries:
  Node: 20.5.1
  npm: 10.3.0
  Yarn: 1.22.22
  pnpm: N/A
Relevant Packages:
  next: 14.2.4 // Latest available version is detected (14.2.4).
  eslint-config-next: 13.0.0
  react: 18.2.0
  react-dom: 18.2.0
  typescript: 5.3.3
Next.js Config:
  output: N/A

Which example does this report relate to?

with-supabase

What browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

next build

Describe the Bug

Running into a bug in my project. I’m trying test a build locally before building my app into a docker container. I continuing to get the same build error response:

  ▲ Next.js 14.2.4
  - Environments: .env

   Creating an optimized production build ...
 ✓ Compiled successfully
 ✓ Linting and checking validity of types
   Collecting page data  ..Error: `cookies` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
    at getExpectedRequestStore (/Users/aesi-kylem/Documents/Gitlab/testing-build/node_modules/next/dist/client/components/request-async-storage.external.js:28:11)
    at u (/Users/aesi-kylem/Documents/Gitlab/testing-build/.next/server/chunks/544.js:10:3754)
    at a (/Users/aesi-kylem/Documents/Gitlab/testing-build/.next/server/app/page.js:1:4507)
    at 1903 (/Users/aesi-kylem/Documents/Gitlab/testing-build/.next/server/app/page.js:1:4014)
    at t (/Users/aesi-kylem/Documents/Gitlab/testing-build/.next/server/webpack-runtime.js:1:128)
    at 9729 (/Users/aesi-kylem/Documents/Gitlab/testing-build/.next/server/app/page.js:1:1631)
    at t (/Users/aesi-kylem/Documents/Gitlab/testing-build/.next/server/webpack-runtime.js:1:128)
    at r (/Users/aesi-kylem/Documents/Gitlab/testing-build/.next/server/app/page.js:1:5582)
    at /Users/aesi-kylem/Documents/Gitlab/testing-build/.next/server/app/page.js:1:5621
    at t.X (/Users/aesi-kylem/Documents/Gitlab/testing-build/.next/server/webpack-runtime.js:1:1206)

> Build error occurred
Error: Failed to collect page data for /
    at /Users/aesi-kylem/Documents/Gitlab/testing-build/node_modules/next/dist/build/utils.js:1268:15
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  type: 'Error'
}
   Collecting page data  .error: script "build" exited with code 1

I’m using the with-supabase template and this error is suggesting a mishandling of the cookies call which is giving the out of scope error. The error seems to bounce from the root / page and my /projects. Both are a fairly standard setup of a page.tsx server async component (default) awaiting fetches from a “use server” actions file that fetches from my supabase DB and passes the data down to client components as props.

Simplified Page.tsx minus the props client pass:

// app/page/page.tsx

import { getLatestProjects } from "@/libs/actions/actions";

async function Page() {
const projects = await getLatestProjects();
return (
 <main className="flex flex-1 flex-col gap-4 p-4 md:gap-8 md:p-8 max-w-[90vw] mx-auto">
   <ul className=" text-black">
     {projects?.map((project) => (
       <li key={project.id}>{project.name}</li>
     ))}
   </ul>
 </main>
);
}

export default Page;

actions.ts:

"use server"

import { createClient } from "@/utils/supabase/server";

const supabase = createClient();

export async function getLatestProjects() {
    let { data: projects, error } = await supabase
  .from('new_projects')
  .select('*')
  .order('end_date', { ascending: false })
  .limit(10);

    if (error) throw error;

    return projects;
}

To troubleshoot I created a fresh new project using npx create-next-app -e with-supabase and copied over only my .env file and the simplified code you see above to test. When running next build i get the same error.

Expected Behavior

No error should be present when running next build with this project, especially, with no extra config changes to any of the boilerplate auth/session/cookie handling code in the with-supabase,

To Reproduce

  1. Pull down or create a fresh Next app using the with-supabase example: npx create-next-app -e with-supabase

  2. Rename the .env.example to .env and provide your NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY

NEXT_PUBLIC_SUPABASE_URL=
NEXT_PUBLIC_SUPABASE_ANON_KEY=
  1. Create a table with some dummy data of at least id and name. Create an actions file in /lib/actions/actions.ts. Paste the below fetch using the supabase client to your dummy data:
import { createClient } from "@/utils/supabase/server";

const supabase = createClient();

export async function getTest() {
    let { data: test, error } = await supabase
  .from('**your_db**')
  .select('*')
  .limit(10);

    if (error) throw error;

    return test;
}
  1. Remove all boilerplate content from app/page.tsx and replace with the following:
// app/page/page.tsx

import { getTest } from "@/libs/actions/actions";

async function Page() {
  const tests = await getTest();
  return (
    <main className="flex flex-1 flex-col gap-4 p-4 md:gap-8 md:p-8 max-w-[90vw] mx-auto">
      <ul className=" text-black">
        {tests?.map((test) => (
          <li key={test.id}>{test.name}</li>
        ))}
      </ul>
    </main>
  );
}

export default Page;

  1. Test that the app runs with next dev and that your dummy data shows on page at http://localhost:3000/
  2. Finally, run next build, this is where it will error our citing Collecting page data ..Error: cookies was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 6
  • Comments: 24 (1 by maintainers)

Most upvoted comments

I was having a similar issue, I was able to fix it by ensuring that my createClient() statements are within the functions of my code. For example, your actions.ts should be updated to the below:

Actions.ts

"use server"

import { createClient } from "@/utils/supabase/server";

export async function getLatestProjects() {
  const supabase = createClient();
    let { data: projects, error } = await supabase
  .from('new_projects')
  .select('*')
  .order('end_date', { ascending: false })
  .limit(10);

    if (error) throw error;

    return projects;
}

can confirm that the problem is in fact usage of createClient() out of function scope aka usage as global variable.

I am also facing same issue, have you been able to resolve this problem?

I was having a similar issue, I was able to fix it by ensuring that my createClient() statements are within the functions of my code. For example, your actions.ts should be updated to the below:

Actions.ts

"use server"

import { createClient } from "@/utils/supabase/server";

export async function getLatestProjects() {
  const supabase = createClient();
    let { data: projects, error } = await supabase
  .from('new_projects')
  .select('*')
  .order('end_date', { ascending: false })
  .limit(10);

    if (error) throw error;

    return projects;
}

@robskinney Thanks, this solution worked. The problem was that when we initialise supabase client outside the scope of a function is that it doesn’t have access to cookies cause cookies aren’t available outside of an http request. Next.js collects static page data when building the project and since cookies are not available at build-time, it throws an error.

Make sure to only initialise this in a function or scope where it has access to cookies, otherwise this error would be thrown.

I have encountered the same problem. What is strange this problem occurs with me only on a specific route. On other route pages where I have basically almost identical logic the problem does not occur.

Interestingly - With the same code, a week ago, everything worked. Isn’t this a problem maybe with Supabase?

I’m using Next 14.2.3 Problem occurs on local server - npm run dev

hmm i am also getting the same error when using supabase/server.ts

import { createServerClient, type CookieOptions } from '@supabase/ssr'
import { cookies } from 'next/headers'

export function createClient() {
  const cookieStore = cookies()

  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        getAll() {
          return cookieStore.getAll()
        },
        setAll(cookiesToSet) {
          cookiesToSet.forEach(({ name, value, options }) =>
            cookieStore.set(name, value, options),
          )
        },
      },
    },
  )
}

It happens when i am making a stripe webhook call and want to save user’s data in supabase, it is working fine it i directly use supabase

import { createClient } from '@supabase/supabase-js'


const supabase = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
)

It seems that this bug is still present. I’m using the exact same code than the with-supabase example and when i press the Sign out button, this bugs shows up and i’m unable to sign out from my account. https://github.com/vercel/next.js/tree/canary/examples/with-supabase All of my createClient() calls are inside functions…

How does it work with unit testing though? How do you unit test those functions, if cookies aren’t available when running unit test with e.g. jest?

Mock them, i guess.

How does it work with unit testing though? How do you unit test those functions, if cookies aren’t available when running unit test with e.g. jest?