Forum Discussion

luk's avatar
luk
Boss
6 years ago

Setting cookie attributes (expiration/domain) in page init

I'm able to create a new cookie on page init with ${http.response.addCookie(http.request.createCookie("name", "value"))} while this does NOT work (but is also stated in the docs, slightly confusing...
  • luk's avatar
    6 years ago

    I was close =)... setting the cookie attributes seems to only work when directly interpolating the variable... that means it has to be written in this way:

    // THIS WILL NOT WORK
    
    <#assign cookie = http.request.createCookie("name", "value") />
    <#assign cookie = cookie.setValue("some manually set value") />
    <#assign cookie = cookie.setHttpOnly(true) />
    // ... etc
    ${http.response.addCookie(cookie)}
    
    // WHILE THIS WILL WORK
    
    <#assign cookie = http.request.createCookie("name", "value") />
    ${cookie.setMaxAge(24*60*60)} // 24 hours
    ${cookie.setDomain(".domain.tld")}
    ${cookie.setPath("/")}
    ${cookie.setValue("some manually set value")}
    ${cookie.setHttpOnly(true)}
    ${cookie.setSecure(true)}
    ${cookie.setComment("Describes what this cookie does")}
    ${http.response.addCookie(cookie)}

    SuzieH I think that should be added to the docs, might save somebody a few hours of research in the future =)