In this blog post, we are going to see, how the cookies are persisted for all the subdomains of SUSI.AI. By this implementation, the session for the user is maintained over all the SUSI.AI websites.
The cookies are persisted over these SUSI.AI websites –
- SUSI.AI Chat – https://chat.susi.ai
- SUSI.AI Skill CMS – https://skills.susi.ai
- SUSI.AI Accounts – https://accounts.susi.ai
All the web clients are developed using ReactJs framework and for the manipulation of cookies in React, a npm package – universal-cookie is used. Firstly, we will see how the cookies are set/created during login, followed by removal of cookies during logout.
- Firstly, we need to import the universal-cookie package into the component and create an instance of it.
Now, we can set a new cookie using this instance of cookies.
- The following snippet sets the cookies after the login is done.
- The cookies.set is a function provided by the package, that takes in three (3) parameters –
- Cookie name
- Cookie vallue
- Options – an object containing the cookies properties
- In the above example, say setting the loggedIn cookie, that contains the access token. We set the cookie name as loggedIn, the cookie value equal to the access token value received from the server response.
- Apart from that, we have set 3 properties of the cookies, by passing an optional options parameter to the set function.
- path – It indicates a URL path that must exist in the requested URL in order to send the Cookie header.
- domain – It specifies allowed hosts to receive the cookie. If unspecified, it defaults to the host of the current document location, excluding subdomains.
- maxAge – It specifies a time duration after which the cookie gets expired.
- It is mainly used, when a user wants to logout. It is used in the Logout component of the client’s codebase.
- An approach to delete/remove a cookie is to set the expiry date of the cookie as Thu, 01 Jan 1970 00:00:01 GMT, which results in the removal of the cookie after a page refresh.
- Following is the code snippet of how the cookies are removed to log-out a user of the website.
- The deleteCookie function takes in 2 params –
- Cookie name
- options – an object containing the cookies properties
- The options parameter needs to be passed while deleting the cookie, as it defines the scope for which the cookie has to be deleted.
- The function creates a string and appends to it the expiry date, path, domain to the cookie name, if provided.
- Finally, it sets the cookie by assigning the string to the document object.
- API Documentation of Cookies –
- Github page for universal-cookie –