Cookies set in middleware not available on "first pass"
Unanswered
American posted this in #help-forum
AmericanOP
Hello!
I have a middleware function which looks like this:
Basically setting a locale cookie if it doesn't exist.
Then I read it like this:
My problem is that the console.log just above will always be undefined on my first load. Like if I open up a page in "private browsing" and visit my website that cookie will not be defined until I reload this page. How can I fix this?
I have a middleware function which looks like this:
export async function middleware(request: NextRequest) {
const hostname = request.headers.get("host")!.replace("www.", "");
const domainLocale = domainTable[hostname] ?? defaultLocale;
const response = NextResponse.next();
const cookieLocale = request.cookies.get("locale")?.value;
const locale = cookieLocale ?? domainLocale;
response.cookies.set("locale", locale, {
expires: dayjs().add(1, "year").toDate(),
});
return response;
}Basically setting a locale cookie if it doesn't exist.
Then I read it like this:
export function getLocale() {
const cookie = cookies().get("locale")?.value;
console.log("🍪 cookie", cookie); // always undefined on first load
return (cookie ?? defaultLocale) as (typeof locales)[number];
}My problem is that the console.log just above will always be undefined on my first load. Like if I open up a page in "private browsing" and visit my website that cookie will not be defined until I reload this page. How can I fix this?
4 Replies
AmericanOP
My workaround now is to also send it as a header, and fall back to that if there's no cookie set
Are you on next 14? I think this is a known issue, when my user first visits my site, I set some cookie for a session id or whatnot, very similar to yours, I have to fallback to what is set in the response header via
This issue should be fixed IIRC in next 15 or a future version of 14:
https://github.com/vercel/next.js/issues/49442
headers() in the server component.This issue should be fixed IIRC in next 15 or a future version of 14:
https://github.com/vercel/next.js/issues/49442
AmericanOP
Yeah, I'm on 14. At least I'm not alone in this workaround then 😅 Thank you, and thanks for the link too!
Nile Crocodile
I have been having this challenge too. What's you experience with next js 15, it seems to be the only one with the fix?