"Error: Invariant: Method expects to have requestAsyncStorage, none available" with cookies
Answered
Pacific herring posted this in #help-forum
Pacific herringOP
I'm tryna access to the cookies in the middleware file.
function (in another file):
middleware.ts
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",
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
29 Replies
Pacific herringOP
Up pls im trying everything
try accessing the cookie using
request.cookies
instead of cookies()
Pacific herringOP
Will try once im back home. Whats the explaination behind request.cookies? Wouldnt it be the same thing as cookies.get?
it is the officially recommended way to get cookies in middleware https://nextjs.org/docs/app/building-your-application/routing/middleware#using-cookies
Answer
Pacific herringOP
Makes sense
Cant wait to try it at home
Will let u know
Pacific herringOP
it worked
this soolution is the only good thing happened today lol thanks
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
Scottish Deerhound
Any solution?
this is the solution
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:
Dashboard component:
supabase-server.js:
I'm really waiting a solution for days. Thanks again.
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.
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;
Scottish Deerhound
Ah thanks anyway. I posted a question and commented:
https://stackoverflow.com/questions/76774517/next-js-and-supabase-method-expects-to-have-requestasyncstorage
https://github.com/vercel/next.js/issues/52176#issuecomment-1653264986
It looks like a bug.
https://stackoverflow.com/questions/76774517/next-js-and-supabase-method-expects-to-have-requestasyncstorage
https://github.com/vercel/next.js/issues/52176#issuecomment-1653264986
It looks like a bug.
Pacific herringOP
yh seems like a bug they better resolve asap
Scottish Deerhound
I guess the problem is in the
cookies
from next/headersNo solution unfortunately
Pacific herringOP
luckily i managed to resolve with my snippet, I think others got workarounds that didnt share
Scottish Deerhound
Thanks
Pacific herringOP
no worries
Scottish Deerhound