title: JavaScript Duplicate Cookies
body: <p>I'm using the Hapi framework for a Node.js application, and the Hapi framework comes with its own Cookie management tools, which i'm using for authentication.</p>
  
  <p>The framework then sets a cookie named session, with a json value encoded to base64. The domain is set to example.com (not .example.com)</p>
  
  <p>Now, the problem lies when i attempt to edit this cookie client-side, by doing the following</p>
  
  <pre><code>document.cookie = 'session=' + btoa(JSON.stringify(_decoded)) + "; path=/; domain=example.com";
  </code></pre>
  
  <p>This actually sets a duplicate cookie with the domain '.example.com'</p>
  
  <p>I haven't asked Javascript to prepend the dot, and i cant seem to get rid of it.</p>
  
  <p>I'm assuming that it is because of this dot, that the cookie is being duplicated. How do i set the domain without it automatically prepending a dot?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I've given up on trying to remove the leading dot, and instead am trying to delete the old cookie and then create a new one. However i still end up with duplicate cookies!</p>
  
  <ol>
  <li>Navigate to /login and enter login details</li>
  <li>Redirected to /account and cookie set by server (WITHOUT Leading Dot)</li>
  <li>Execute Javascript to delete and re-create cookie</li>
  <li>1 cookie now exists and it has a Leading Dot before the domain</li>
  </ol>
  
  <p>The above behaviour is good, however the following also happens, which is bad</p>
  
  <ol>
  <li>Navigate to /login and enter login details</li>
  <li>Redirected to /account and cookie set by server (WITHOUT Leading Dot)</li>
  <li>Navigate to /example</li>
  <li>Execute Javascript to delete and re-create cookie</li>
  <li>2 cookies now exists, one with the leading dot(created by JS) and one without (created by server)</li>
  </ol>
  
  <p>The code i'm using is</p>
  
  <pre><code>API.Session = {
      Encoded : function () { return document.cookie.replace(/(?:(?:^|.*;\s*)session\s*\=\s*([^;]*).*$)|^.*$/, "$1")},
      Decoded : function () { return JSON.parse(atob(this.Encoded()))},
      Update : function (_decoded) { 
          document.cookie = 'session=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
          document.cookie = 'session=' + btoa(JSON.stringify(_decoded)) + "; path=/; domain=example.com;";      
      }
  }
  
  API.Helpers.ShowAdvancedOptions = function () {
      var s = API.Session.Decoded()
      s.ShowAdvancedOptions = true
      API.Session.Update(s)
  }
  </code></pre>