Node : How to identify if any user is opening the website more than one time

Viewed 28

How can I identify if the same user is opening the website or not with node/express backend? I've tried to set a cookie but don't know why it's removed automatically

1 Answers

Here's just a sample of how you can achieve it.

First install this npm package:

npm install express cookie-parser

Then a general setup:

const express = require('express')
const cookieParser = require('cookie-parser')

//to setup express app
const app = express()
app.use(cookieParser());

Bootstrap the rest of your liking.

Here's the important part for the cookies:

//an example route for setting cookies
app.get('/setcookie', (req, res) => {
    res.cookie(`Cookie token name`,`encrypted cookie string Value`,{
        maxAge: 5000,
        // expires works the same as the maxAge
        expires: new Date('01 12 2021'),
        secure: true,
        httpOnly: true,
        sameSite: 'lax'
    });
    res.send('Cookie have been saved successfully');
});

If you want you may use this route to check the cookies from your browser (or look into the developer tools if your cookie name is set):

// get the cookie incoming request
app.get('/getcookie', (req, res) => {
    //show the saved cookies
    console.log(req.cookies)
    res.send(req.cookies);
});

So in a nutshell this should do the trick :)

More details and examples of this approach can be found here.

Related