Unable to set cookie in sling model class | Community
Skip to main content
Mario248
Level 7
May 9, 2025

Unable to set cookie in sling model class

  • May 9, 2025
  • 1 reply
  • 737 views

I am trying to set cookie inside my sling model class but the cookie is not setting. Here is my sling model class

 

@Model( adaptables = {SlingHttpServletRequest.class}, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL) public class TestModel { @SlingObject private SlingHttpServletRequest request; @SlingObject private SlingHttpServletResponse response; @PostConstruct private void init() { Cookie cookie = new Cookie("categoru", "11111"); cookie.setMaxAge(86400); // in seconds, 86400 = 24 hours. response.addCookie(cookie); // server response response.setStatus(200); } }

 

But I am able to set the cookie successfully when I try to setup a cookie using servlet. Here is my servlet code.

@8220494( service = { Servlet.class }, property = { SLING_SERVLET_PATHS + "=/bin/setCookieExample" } ) public class TestModelSer extends SlingAllMethodsServlet { @9944223 protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { Cookie cookie = new Cookie("visitedCookieServletExample", "123"); cookie.setMaxAge(86400); // in seconds, 86400 = 24 hours. response.addCookie(cookie); // server response response.setStatus(200); } }

Any idea what is missing in sling model class?

1 reply

abhishekanand_
Community Advisor
Community Advisor
May 9, 2025

Hi @mario248 

the code can work under very specific conditions, but it’s not recommended nor guaranteed to be reliable. If the Sling Model is adapted from a SlingHttpServletRequest, and injected before the response is committed, you technically can access and mutate the SlingHttpServletResponse. 

 

may be the response might have already been committed or flushed when the model is created during rendering.

 

but it’s not recommended or reliable use a Filter or Servlet to set the cookie, and store state in local/sessionStorage.

https://sourcedcode.com/blog/aem/set-cookie-example-of-aem-servlet-and-sling-model

you can follow this as well for examples

Abhishek Anand
Mario248
Mario248Author
Level 7
May 9, 2025

Sling model may be not be recommended. How are you saying servlet is also not reliable to set cookie? what is recommended way to setup a cookie ?

abhishekanand_
Community Advisor
Community Advisor
May 12, 2025

Hi @mario248

 

In this line "but it’s not recommended or reliable to use a Filter or Servlet to set the cookie and store state in local/sessionStorage.", perhaps you misinterpreted it, and I apologize for how I expressed it here.

 

i mentioned to use a Filter or Servlet to set the cookie, and models are not recommended

Abhishek Anand