Findmypast Tech

Creating cookies in Javascript

Leigh Shepperson Leigh Shepperson
Reading time: 1 min

The Hints UI application needs to create session cookies that are shared between different sub-domains of FindMyPast and we need to create the cookies using JavaScript (ReactJS, HapiJS). The solution is not difficult, but it is easy to go down the wrong path.

Problem

We want to track users who come from partners (3rd party) and we need to do this by using cookies. For example, if a partner has partnerId = 65340234-a07e-4339-b218-e40a6b3803b0 and lands on http://acceptance.findmypast.com/hints-ui/, then we expect a session cookie to be created containing the partnerId. Additionally, this cookie should also be visible from http://acceptance.search.findmypast.com/search-world-records.

Solution

You can create a session cookie by just setting the cookie property on the document object. To make sure it is visible from all sub-domains of findmypast.com, you need to include domain = findmypast.com. For example:

document.cookie = 'partnerId= 65340234-a07e-4339-b218-e40a6b3803b0; path=/; domain=findmypast.com;

If this is created on a sub-domain, then this will be accessible on the domain and also the other sub-domains of findmypast.com. However, this will not be visible from findmypast.co.uk or findmypast.com.au. To do this, you need to inspect the windows.location.hostname property and retrieved the appropriate domain.

Note, to create a persistent cookie, you need to set the expires attribute to some point in the future. For example:

document.cookie = 'partnerId= 65340234-a07e-4339-b218-e40a6b3803b0; path=/; expires=Mon, 11 Jun 2018 12:00:00 UTC; domain=findmypast.com;

Testing:

Our environmental setup used a combination of HapiJS and RequireJS. By default, the application host is localhost or the operating system default. If you want to create a cookie under findmypast.com on your local machine, you need to do two things:

  • Open the hosts file (located at C:\Windows\System32\drivers\etc) and add a sub-domain of the domain you want to test. For example,
127.0.0.1 local.hints.ui.findmypast.com
  • In server.js, edit the host property to match this sub-domain
var server = new Hapi.Server();
server.connection({
    port: args.port
    host: "local.hints.ui.findmypast.com"
});

If you run the application using gulp or otherwise, it will now be served from local.hints.ui.findmypast.com. Cookies created here will be shared with other sub-domains of findmypast.com.