Working with Cookies to setup Authentication in Javascript

Universal Cookie

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.

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 :)

--

--

--

Building influencerbit.com, 📍Bengaluru

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to create an API for Metascraper.js with Vercel and Typescript

Working with React Hooks

JavaScript Modules in the Browser in 2021

JWT with JavaScript and rails PART 2

Deploy your iOS App on App Store without a Mac

How to write lodash methods in JavaScript?

5 Reasons To Hire Angular JS Developers For Your Web App Development

How to Use Two-Way Data Binding Between Components

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aman Kumar

Aman Kumar

Building influencerbit.com, 📍Bengaluru

More from Medium

Some Changes in React Router v6

React Router DOM v6 — Part — I

Protected Routes with react-router-dom v6

ESlint, Prettier, EditorConfig and Husky For react typescript Project