Cookies returning undefined in the middleware
Answered
Holland Lop posted this in #help-forum
Holland LopOP
I'm using Next.js 14.2.5 as the frontend and Nest.js as backend. Authentication is handled by Nest.js backend.
API: /signin
A successful authentication will result in cookie set by the backend itself in the browser as access_token, refresh_token and expires_at.
Cookies are HttpOnly=true, Secure=true and SameSite=None
I can see the cookies there in the browser by inspecting Application tab of Developer Tools.
The problem is, when I try to check if a cookie exists there or not using cookies from next/headers in the middleware to secure routes, it says undefined. Like there is no cookie with the name "access_token". But there are other cookies as well like csrf and url, which were created by NextAuth(which I previously tried and not using now but not completely removed) and I get those cookies by name like "csrf".
I tried inspecting the Application tab while reloading the page. And I found something weird that every time I refresh page cookie disappears and appears again after initial render of the page, like after skeleton/loading component appears.
Any idea what causing this issue? Did I miss something?
Any help would be appreciated. Thanks!
API: /signin
A successful authentication will result in cookie set by the backend itself in the browser as access_token, refresh_token and expires_at.
Cookies are HttpOnly=true, Secure=true and SameSite=None
I can see the cookies there in the browser by inspecting Application tab of Developer Tools.
The problem is, when I try to check if a cookie exists there or not using cookies from next/headers in the middleware to secure routes, it says undefined. Like there is no cookie with the name "access_token". But there are other cookies as well like csrf and url, which were created by NextAuth(which I previously tried and not using now but not completely removed) and I get those cookies by name like "csrf".
I tried inspecting the Application tab while reloading the page. And I found something weird that every time I refresh page cookie disappears and appears again after initial render of the page, like after skeleton/loading component appears.
Any idea what causing this issue? Did I miss something?
Any help would be appreciated. Thanks!
3 Replies
Holland LopOP
import { cookies } from "next/headers";
const cookiesInfo = cookies();
const allCookies = cookiesInfo.getAll();
Here in this,
allCookies
only showing 1 of 4 cookies.But I can verify the existence of all 4 cookies in the Dev tools > Application > Cookies
Answer
Holland LopOP
Oh mahn! This fixed my issue. I never knew there was a
You saved my day!
Thanks a lot @Clown !
domain
attribute with Set-Cookie.You saved my day!
Thanks a lot @Clown !