i need to create unique id in node.js without register

1.1k Views Asked by At

I need to receive unique id in node.js when user not login or register. I used the request-ip package also used req.headers['x-forwarded-for'] and req.connection.remoteAddress but The IP in these commands varies according to the Internet and is not unique to each browser

1

There are 1 best solutions below

0
Pouria Moosavi On

You can create a middleware for your application. In this middleware check if the user is not log in and the request does not contain some special header (for example ["first-token"]) then create a big random string:

const token = crypto.randomBytes(64).toString('hex');

and send it to your client. for example:

res.json({firstToken: token, /*Other fields you may need to send*/});

Then in your client side store it in cookie or local storage.
Cookie:

document.cookie = document.cookie + "; firstToken=" + firstToken

LocalStorage:

localStorage.setItem("firstToken", firstToken);

And after that you should send this cookie in every request you send to the server. In this example in ["first-token"] header.

This way you assign a unique random string to user and you do not change it until they clear their browser data.