javascriptangularjscookiesangular-cookies

What would prevent AngularJS $cookies from writing a cookie?


I'm attempting to write a simple cookie using the AngularJS v1.5.x $cookies service. The dependencies are all correct, as I can read a cookie. However, neither write nor edit are working.

For example:

var blah = $cookies.get('mysite_auth');
console.log('old: ' + blah);

$cookies.put('mysite_auth', 'blech');

blah = $cookies.get('mysite_auth');
console.log('new: ' + blah);

... results in the following output:

old: ZmVhZDE ... =
new: ZmVhZDE ... =

No errors are thrown. The same occurs when attempting to write a new cookie:

$cookies.put('someCookie', 'yup');

I can write a cookie in my controller like so:

document.cookie = 'TEST=TESTVALUE';

What might be the cause of this?


Solution

  • It turns out that Angular $cookies was writing the cookie, but we had a domain/path problem. Because our Angular apps live outside our back end app directory, the page URL doesn't match the server path. If I visited the actual path, while the page didn't properly load, the cookie was present.

    We resolved the issue with this domain/path configuration:

    $cookies.put('myCookie', true, {
        domain: '.mydomain.com',
        path: currentUrl,
        expires: exp
    });