In this blog, we will be looking at how to work with cookies to setup authentication or session management in your web application.
Check this Session Management: Cookies vs localstorage for why we are using cookies to handle session management.
Session Management across Subdomains: Localstorage vs Cookies
Cookies work across subdomains while localstorage can’t be scoped to do so
We can work with cookies via HTML or JS directly, but there are various npm packages to ease this out for us. We will use universal-cookies npm package for this.
1. Install Universal-Cookie npm package
npm install universal-cookie --save
2. Add this file content to your repository in a new file.
3. Now, you can call these functions anywhere from your repository.
a. After successful login response from the server, you have to set the authentication token in cookies, you can do that directly via server or
Return the token in response and pass that token to setToken function, and it will be done by the browser.
b. Logging off user, call logout function from anywhere and the cookie will be removed successfully.
Pros of having cookies controlling function at one place:
1. You can execute setting token, getting back token, log out by calling single line functions anywhere.
2. Say at any time in future, you change your domain name, or cookies identifier if you have separate cookies interaction functions at server and browser. You need to change the same thing over and over. Remember DRY (Don’t Repeat yourself), so don’t repeat and keep them all in one place.
Thanks for reading, hope this helps :)