cookies() does not work, "Invariant" issue
Answered
Northeast Congo Lion posted this in #help-forum
Northeast Congo LionOP
Hey guys,
I'm getting this error:
Invariant: Method expects to have requestAsyncStorage, none available
when I try cookies().set.
for the API route.
The frontend does:
I've tried a huge number of things, but it appears that somehow the backend code is being used by the frontend which is causing this. Is there some way the file (which is in
I'm getting this error:
Invariant: Method expects to have requestAsyncStorage, none available
when I try cookies().set.
import { login } from "../../backendlib/authentication";
import { UserLoginData } from "../../types/authTypes";
import { cookies } from 'next/headers'
// post route for logging in
export default async function POST(req:any, res:any) {
//log the user in and assign the user a session
const { email, password, rememberMe } = req.body;
const data: UserLoginData = {
email,
password,
rememberMe
}
const result = await login(data);
if (result.success) {
//set the cookie to the token
console.log(req.cookies)
cookies().set('token', result.data.token, {
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
path: '/'
})
res.status(200).json({success:true});
} else {
res.status(400).json({success:true, data:{message:result.data.message}});
}
}for the API route.
The frontend does:
const response = await fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data),
})
const result = await response.json()I've tried a huge number of things, but it appears that somehow the backend code is being used by the frontend which is causing this. Is there some way the file (which is in
pages/api btw) is being consumed as a frontend feature?96 Replies
Northeast Congo LionOP
Looks like an error in nextJS.
https://github.com/vercel/next.js/issues/52176
is the only workaround doing something manual like:
https://github.com/vercel/next.js/issues/52176
is the only workaround doing something manual like:
res.setHeader('Set-Cookie',
cookie.serialize('token', data.jwt),
{
httpOnly: true,
maxAge: 60 * 60 * 24 * 7,
sameSite: 'strict',
path: '/'
})?Forest bachac
try getting rid of the console.log req.cookies and instead do cookies().getAll
Northeast Congo LionOP
👠30 secs
Forest bachac
also for your cookies.set it should be like this
cookies().set({
name: 'name',
value: '',
expires: new Date('2016-10-05'),
path: '/', // For all paths
})it shouldnt have two of them outside of the object
Northeast Congo LionOP
cookies().getAllI think the error is coming from the cookies() function
Forest bachac
dont think so
its also
cookies().getAll() its a functionNortheast Congo LionOP
I know
it threw an error
Forest bachac
whats the error
Northeast Congo LionOP
same thing as before.
the problem is the cookies() function.
error node_modules\next\dist\client\components\headers.js (50:14) @ cookies
- error Error: Invariant: Method expects to have requestAsyncStorage, none available
at cookies (webpack-internal:///(api)/./node_modules/next/dist/client/components/headers.js:46:15)
at POST (webpack-internal:///(api)/./pages/api/login.ts:22:95)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
digest: undefined
}Forest bachac
what is on lne 50
Northeast Congo LionOP
No idea, the function doesn't go to line 50
it's 30 lines long
Forest bachac
whats on headers.js line 50?
Northeast Congo LionOP
but that's next/dist/client/components/headers.js
Forest bachac
or login.ts line 22
login.ts line 22?
Northeast Congo LionOP
login.ts line 22 is a random-ass part of the code.
Forest bachac
paste it
Northeast Congo LionOP
secure: process.env.NODE_ENV === 'production',Forest bachac
quite literally part of the cookies()
did you not update your cookies.set?
cookies().set({
name: 'name',
value: '',
expires: new Date('2016-10-05'),
path: '/', // For all paths
})this is the correct format
Northeast Congo LionOP
sorry, was focused on other stuff.
it's been changed now
Forest bachac
ok. does it work?
Northeast Congo LionOP
error node_modules\next\dist\client\components\headers.js (50:14) @ cookies
- error Error: Invariant: Method expects to have requestAsyncStorage, none available
at cookies (webpack-internal:///(api)/./node_modules/next/dist/client/components/headers.js:46:15)
at POST (webpack-internal:///(api)/./pages/api/login.ts:22:95)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
digest: undefined
} expires: new Date('2016-10-05'),Forest bachac
paste your whole thing
Northeast Congo LionOP
import { login } from "../../backendlib/authentication";
import { UserLoginData } from "../../types/authTypes";
import { cookies } from 'next/headers'
// post route for logging in
export default async function POST(req:any, res:any) {
//log the user in and assign the user a session
const { email, password, rememberMe } = req.body;
const data: UserLoginData = {
email,
password,
rememberMe
}
const result = await login(data);
if (result.success) {
//set the cookie to the token
console.log("Cookies get all: ",cookies().getAll())
cookies().set({
name: 'token',
value: '123',
expires: new Date('2016-10-05'),
path: '/', // For all paths
})
res.status(200).json({success:true});
} else {
res.status(400).json({success:true, data:{message:result.data.message}});
}
}Forest bachac
did you rerun it?
Northeast Congo LionOP
yeah.
Forest bachac
what are you using
yarn, npm?
Northeast Congo LionOP
npm
Forest bachac
npm run dev?
Northeast Congo LionOP
npm run devyou got it lol
Forest bachac
can you like ctrl-c and can you try running npm run dev again?
Northeast Congo LionOP
I'm trying that now.
But I've tried that previously
Ok restarted. Same issue
European sprat
isn't cookies() an app directory helper?
Northeast Congo LionOP
https://nextjs.org/docs/app/api-reference/functions/cookies this is what I was using
European sprat
yeah that's app directory and it looks like your API route is pages
Forest bachac
wait are you not using app dir
doesnt matter
cookies isnt meant for the route handler
you set cookies in response.cookies.set
Northeast Congo LionOP
looking up the official nextjs tutorial that told me to do it exactly this way
Forest bachac
no but thats the app dir guide
yet here you are
Northeast Congo LionOP
you set cookies in response.cookies.setresponse.cookies.set is not a function, tried that
Forest bachac
and your whole file is like app dir stuff but your using pages
@DirtyCajunRice | AppDir cookies isnt meant for the route handler
Forest bachac
whats it meant for then? bc im using it rn j fine but in a function called by the route handleer
@Northeast Congo Lion > you set cookies in response.cookies.set
response.cookies.set is not a function, tried that
dude. why would that be a function if you dont have a response object
@DirtyCajunRice | AppDir cookies isnt meant for the route handler
European sprat
you can .set() in routes and actions now
@European sprat you can .set() in routes and actions now
doesnt mean you should. obfuscates your code.
@DirtyCajunRice | AppDir dude. why would that be a function if you dont have a response object
Northeast Congo LionOP
I used "res" not "response" lol
Northeast Congo LionOP
res.cookies.set is not a function.
it is in app dir
if you arent in app all these people have wasted their time
@DirtyCajunRice | AppDir i use it in actions.
Forest bachac
but it works with route handler
in app
Northeast Congo LionOP
it's pages
It's small but I did mention that
cookies() is an app dir function
European sprat
don't use cookies(), look here and search for cookies to see how to manage cookies in pages: https://nextjs.org/docs/pages/building-your-application/routing/api-routes
Northeast Congo LionOP
I swear to god I followed the tutorial step by step
I can't find said tutorial now
of course
Northeast Congo LionOP
ikr haha
"sus"
xD
if you are brand new, you should do app dir not pages. it will still be supported for a long time but no new features
Northeast Congo LionOP
I'm def feeling crazy now
well, I can't find why the heck I tried doing that, 99% chance I just didn't notice the toggle between pages/appDir. In light of that, let's mark this as complete with "You can't use cookies() with pages"
@Northeast Congo Lion well, I can't find why the heck I tried doing that, 99% chance I just didn't notice the toggle between pages/appDir. In light of that, let's mark this as complete with "You can't use cookies() with pages"
haha. just right click the message of the user that made the message and theres a bot command for it
Northeast Congo LionOP
I'll have to wait on that as I just went to sleep
Well to bed
Am on mobile bow
Now*
I'll also need to remind myself to say that in the issue I linked
Northeast Congo LionOP
You cant use cookies() with pages routes.
Answer