Java vs Javascript: getting different values for browser cookie



So I have the following Java

for (Cookie cookie : getRequest().getCookies()) {

   if (cookie.getName().equals((String) Constants.class.getDeclaredField(get('mycookie',String.class)).get(null))) {

   value = cookie.getValue();



and it's returning some value to my HTL

<sly data-sly-use.courseBookmarkCookie1="${'com.myhost.core.impl.view.components.GetCookieHelper}"></sly>

<p id="doccookiejava">bookmark cookie (from java): ${courseBookmarkCookie1.value}</p>

The problem is when I do the same thing using javascript,

<script type="text/javascript">





I've encountered instances (on page refresh) where the cookie from Java is empty while document.cookie (from javascript) has a value and vice versa.

Any ideas on how to fix it? or perhaps anything I should be looking at?

I am not seeing the same issue when viewing the page on my local instance of AEM.


edit: I've tried my page on author and publisher (view as published) and they are working fine. seems the behavior happens when using the dispatcher.






I think it might be happening because the pages are cached in dispatcher and java file will not be executed once the page is cached in dispatcher. Javascript will execute on browser so always get the latest cookie value.

In order to read the value in java, page should not be cached in dispatcher but it will have performance issues as everytime it will hit publisher.

Hope it gives some idea related to your issue.