DEV Community

Cover image for I love cookies (ExpressJS+cookies)
Sumit Roy
Sumit Roy

Posted on • Updated on

I love cookies (ExpressJS+cookies)

Installing Node.js

Though my web-app is a three screen idea some of the features are taken for granted by us such as login, register, dashboard, and search. So I started my web-app with the most basic login and registration system anyone can build.

First of all, I installed node.js and npm on my laptop. To see the installing instructions go to this guide.

For the love of Cookies

Yes, most of the developers love cookies and me too. I implemented the login and registration part using a package cookie-parser, which is used for storing cookies in your browser. Hasura returns an authorization token, user id and roles when a user signs in.

{
    "hasura_id": 70,
    "hasura_roles": [
        "user"
    ],
    "auth_token": "9zsbtjosat6xqcwsj32nrokxobcrz8sb"
}

With the help of cookie-parser, I stored the hasura_id and auth_token in cookies and used those whenever required for making queries in the database.

For setting cookies:-

res.cookie("userId", json['hasura_id']);
res.cookie("userName", username);
res.cookie("Authorization", json['auth_token']);

And for retrieving those

const user = req.cookies.Authorization;

This is how I checked whether my code is working or not
cookies set

With logout, the cookies got deleted and the session at hasura also ends so that authorization token gets invalid.

res.clearCookie('Authorization');
res.clearCookie('userName');
res.clearCookie('userId');

cookies reset

So this was the basic implementation of user account activity using cookie-parser in ExpressJS which I used for my web app SnipCode.

Here is the index of all the post regarding this series of snipcode developemnt

Part I: App Idea
Part II: App prototype
Part III: Local Development
Part IV: G for Git
Part V: Data Modeling
Part VI: Data & Auth APIs
Part VII: Basic Functionalities
Part VIII: App Screen 1
Part IX: App Screen 2
Part X: App Screen 3
Part XI: User Reviews
Part X: Final Submission

Liked my post?

Top comments (1)

Collapse
 
tecnomage profile image
vini braga

great article with a lot of,good, information.