Invariant: Method expects to have requestAsyncStorage, none available
Asked Answered
A

10

21

I am trying to retrive the data of a user from mongodb atlas using prisma client and I write this code for the fetching of the data and It shows error, Here the prisma client code are written in the prismadb file which is imported as prisma

import { NextApiRequest, NextApiResponse } from "next";
import prisma from "./prismadb";
import { getServerSession } from "next-auth";

const serverAuth = async (req: NextApiRequest, res: NextApiResponse) => {
    try {
        const session = await getServerSession(req);

        if (!session?.user?.email) {
            throw new Error('Not signed in');
        }

        const currentUser = await prisma.user.findUnique({
            where: {
                email: session.user.email,
            }
        });

        if (!currentUser) {
            throw new Error('Not signed in');
        }

        return { currentUser };
    } catch (error:any) {
        // res.status(500).json({ error: `&{err.message}` });
        res.status(500).json({ error: error.message });
        return;
    }
};

export default serverAuth;

I have given the try and catch and this error shows up. I have asked in the chat GPT and it suggests that this may be due to some error between next.js and next-auth and in teh official GitHub account of the Issue is closed but I don't understand any thing

Here are the reference links:

and in next-auth https://github.com/nextauthjs/next-auth/issues/6989

Auxiliaries answered 16/5, 2023 at 4:27 Comment(1)
This seems to be a Next.js issue: github.com/vercel/next.js/issues/45371 . We will need to wait for the Next.js team to action this.Greenway
S
19

If you're getting this error whiles using next13, make sure the file in which you have getServerSession is actually a server file. include "use server" at the top of your page.

getServerSession has to be called in a server component.

Soubriquet answered 13/8, 2023 at 22:13 Comment(1)
@PabloZehle Exactly.Siler
K
6

Found a solution in this thread

import { createServerComponentClient } from "@supabase/auth-helpers-nextjs";
import { Database } from "@/lib/types/schema";
import { cookies } from 'next/headers'
import { cache } from 'react';

export const createServerClient = cache(() => {
    const cookieStore = cookies()
    return createServerComponentClient<Database>({
        cookies: () => cookieStore
    })
})

export async function GET() {
    const supabase = createServerClient()

    const { data, error } = await supabase.from('').select('')

    return data
}

Let me know if this works for you.

Kentonkentucky answered 29/7, 2023 at 17:26 Comment(0)
A
1

if you use getServerSideProps() and NextAuth/Auth.js make sure you give correct arguments:

import { getServerSession } from 'next-auth';

export async function getServerSideProps(context) {
  const session = await getServerSession(context.req, context.res, options);
}
Ashraf answered 20/8, 2023 at 9:1 Comment(0)
L
1

To resolve this error: Invariant: headers() expects to have requestAsyncStorage, none available.

You can inject request and response in getServerSession method in your api route file

import { NextApiRequest, NextApiResponse } from "next";
import { authConfig } from "@/pages/api/auth/[...nextauth]";
import { getServerSession } from "next-auth";
import client from "@/lib/prismadb";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  const session = await getServerSession(req, res, authConfig);
  if (!session.user) {
    return res.status(401).json({ error: "Unauthorized" });
  }
}

Cheers ;-)

Lh answered 9/11, 2023 at 7:16 Comment(0)
O
1

Originally I had the following, but that was throwing an error. Notice where I had initialised cookieStore.

const cookieStore = cookies();
export const createServerSupabaseClient = () => {
  return createServerClient(
    supabaseUrl,
    supabaseAnonKey,
    {
      cookies: {
        get(name: string) {
          return cookieStore.get(name)?.value;
        },
        set(name: string, value: string, options: CookieOptions) {
          cookieStore.set({ name, value, ...options });
        },
        remove(name: string, options: CookieOptions) {
          cookieStore.set({ name, value: "", ...options });
        },
      },
    }
  );
}

Once I moved inside the function, everything worked as expected.

export const createServerSupabaseClient = () => {
  const cookieStore = cookies();

  return createServerClient(
    supabaseUrl,
    supabaseAnonKey,
    {
      cookies: {
        get(name: string) {
          return cookieStore.get(name)?.value;
        },
        set(name: string, value: string, options: CookieOptions) {
          cookieStore.set({ name, value, ...options });
        },
        remove(name: string, options: CookieOptions) {
          cookieStore.set({ name, value: "", ...options });
        },
      },
    }
  );
}
Owenism answered 30/12, 2023 at 11:13 Comment(0)
A
0

In my case I was using using:

import {NextResponse, NextRequest} from 'next/server';
import { cookies } from 'next/headers';

And then inside my middleware.ts

export async function middleware (request: NextRequest) {
  const coo = cookies().get('autho');
  ...

Getting the same error...

But I can solve it like this:

import {NextResponse, NextRequest} from 'next/server';
 
export async function middleware (request: NextRequest) {
  const coo = request.cookies.get('autho');
....

PS: NextJS Version 13.4.19

Admissible answered 25/9, 2023 at 14:48 Comment(0)
E
0

I was getting the same error in vercel-ai-chatbot repository from supabase-community. but finally solved the issue by replacing runtime 'edge' to 'nodejs'

  export async function Header() {
  const cookieStore = cookies()
  const session = await auth({ cookieStore })
  return (
   .......
  )
Evelineevelinn answered 24/10, 2023 at 8:26 Comment(0)
C
0

I encountered the same error because I was using getKindeServerSession in conjunction with an action in Nextjs 13.5.5. The build kept failing until I changed

const { getUser } = getKindeServerSession()

const user = getUser();

export async function GET() {
// [...]

to

const { getUser } = getKindeServerSession();

export async function GET() {
  
  const user = getUser();
  // [...]
Chloroform answered 25/10, 2023 at 8:1 Comment(0)
I
0

Today when I learn Mosh's Next course,I meet the same error.

Error:Unhandled Runtime Error Error: Invariant: headers() expects to have requestAsyncStorage, none available.

Reason:I use "const session = await getServerSession(authOptins)",But I put "use client" on the top.

Solution:I put 'use client' into the right component.

Isocracy answered 3/12, 2023 at 8:21 Comment(0)
N
0

I got this error but mine was about cookies and not headers while getting user for supabase user in a server component like so:

  //Get user
  async function getUser() {
    "use server";
    const cookieStore = cookies();
    const supabase = await createSupabaseServer(cookieStore);
    const {
      data: { user },
    } = await supabase.auth.getUser();
    return user;
  }

  const user = await getUser();

The problem there was that const user = await getUser(); was not enclosed in an async function. So I moved the whole getUser() function and other functions depending on const user inside the async page function. Initially user was being used by several functions outside page so I left it out there and did not notice it was not enclosed in an async function. The error only appeared during build time, am glad it showed up at that time.

Nut answered 15/1 at 13:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.