Next.js Discord

Discord Forum

"Error: Invariant: Method expects to have requestAsyncStorage, none available" with cookies

Answered
Pacific herring posted this in #help-forum
Open in Discord
Avatar
Pacific herringOP
I'm tryna access to the cookies in the middleware file.

function (in another file):
const getLoggedCookie = async() => {
    const isLogged = cookies().has('logged');;
    return isLogged
}

middleware.ts
const middleware = async (request: NextRequest) => {
    if (request.nextUrl.pathname.startsWith('/signin')) {
        const isLogged:boolean = await getLoggedCookie();

        if(isLogged == true) {
            return NextResponse.redirect(new URL('/', request.url))
        }
    }
}


error upon visiting /signin:
Error: Invariant: Method expects to have requestAsyncStorage, none available
the error is on the function to get cookies. Is it not possible to access cookies in the middleware file? My goal is to check if the user has the cookie "logged", and redirect them to localhost:3000/ if he tries to access to the log in page if he is already logged in. Im on the "next": "^13.4.9",
Answered by joulev
it is the officially recommended way to get cookies in middleware https://nextjs.org/docs/app/building-your-application/routing/middleware#using-cookies
View full answer

29 Replies

Avatar
Pacific herringOP
Up pls im trying everything
Avatar
try accessing the cookie using request.cookies instead of cookies()
Avatar
Pacific herringOP
Will try once im back home. Whats the explaination behind request.cookies? Wouldnt it be the same thing as cookies.get?
Avatar
it is the officially recommended way to get cookies in middleware https://nextjs.org/docs/app/building-your-application/routing/middleware#using-cookies
Answer
Avatar
Pacific herringOP
Makes sense
Cant wait to try it at home
Will let u know
Avatar
:CapooNodYellow:
Avatar
Pacific herringOP
it worked
this soolution is the only good thing happened today lol thanks
Avatar
Tomistoma
this bug is present since 13.4.8 you cannot use headers or cookies in pages.tsx, layout.tsx, functions like generateMetadata or middleware. There is a issues open
Avatar
Scottish Deerhound
Any solution?
this is the solution
Avatar
Scottish Deerhound
Thank @Pacific herring. I saw this link before, but I didn't get it clearly. Could you share what is the wrong, and what should I change here?

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
}


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
    }
}


I'm really waiting a solution for days. Thanks again.
Avatar
Pacific herringOP
I'm a rookie my man, I ain't know how to help you here but I just read the wiki and says that you can respond returning a Response / NextResponse. Supposed you're on NexJS13, so your middleware would be:
    return new NextResponse(
      console.log("ERROR [PENDING] DETAILS: ", JSON.stringify(pending, null, 2))
    )
@Scottish Deerhound also if I were you I'd open a new thread in the help-forum so people can look better at your problem and other users in future will be able to track better the given solution
This is my middleware if you need to look at it btw
import { NextRequest, NextResponse } from "next/server";

const middleware = async (request: NextRequest) => {
    if (request.nextUrl.pathname.startsWith('/signin')) {
        console.log("Middleware");
        console.log(request.url)

        if(request.cookies.has('logged')) {
            console.log("redirect")
            return NextResponse.redirect(new URL('/', request.url))
        }
    }
}
export default middleware;
Avatar
Pacific herringOP
yh seems like a bug they better resolve asap
Avatar
Scottish Deerhound
I guess the problem is in the cookies from next/headers
No solution unfortunately
Avatar
Pacific herringOP
luckily i managed to resolve with my snippet, I think others got workarounds that didnt share
Avatar
Scottish Deerhound
Thanks
Avatar
Pacific herringOP
no worries
Avatar
Scottish Deerhound