cookies-next icon indicating copy to clipboard operation
cookies-next copied to clipboard

Cannot read cookie on first request in NextJs Custom Document

Open dopoto opened this issue 1 year ago • 0 comments

I'm using the following code to set a cookie on the client-side:

import { getCookie, setCookie } from 'cookies-next'; // v4.0.0
setCookie('cookieName', 'cookieValue');

I then need to read that cookie on the server side, in a NextJs custom document (https://nextjs.org/docs/pages/building-your-application/routing/custom-document):

static async getInitialProps(ctx: DocumentContext): Promise<DecoratedDocumentInitialProps> {
	const initialProps = await Document.getInitialProps(ctx);
	// The cookie string below does not include 'cookieName' on first refresh
	// 'cookieName' appears however after I refresh a few times
	const cookie = ctx?.req?.headers?.cookie;
}

But the problem is that the cookie is not present after the first refresh. It takes a few page refreshes for it to show up on the server side. Do you know why? Is there a workaround? Strange - I cannot reproduce this on a local env, only on a NextJs Vercel env.

dopoto avatar Sep 12 '23 06:09 dopoto