Expand my Community achievements bar.

Submissions are now open for the 2026 Adobe Experience Maker Awards.

Unable to set cookie in sling model class

Avatar

Level 9

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.

@component(
        service = { Servlet.class },
        property = {
                SLING_SERVLET_PATHS + "=/bin/setCookieExample"
        }
)
public class TestModelSer extends SlingAllMethodsServlet {

    @Override
    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?

4 Replies

Avatar

Community Advisor

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

Avatar

Level 9

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 ?

Avatar

Community Advisor

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

Avatar

Level 2

Agreed