Muhammad Umer
Muhammad Umer

Reputation: 18097

Nodejs: How do you differentiate between users?

I am new to backend. Only way i can think of is this:

  1. at visit if doesn't have cookie then do next step
  2. generate unique id and then set it as cookie
  3. then upon every request check if that id is present in database and if not go to step 1.
  4. if it's present then fetch data under that id and respond as needed.

Now is it safe?, Is it logical. What does actually happen.

Scenario to use in:

This is meant for not logged in users. Basically, users visit my site, click something that takes time.. so user is redirected to a page with waiting gif all the while using ajax (long polling) server is requested for results. Now to differentiate between requests from multiple users i am thinking this will work. It's important because data i'm going to be sending back is going to be private from 3rd party.

Upvotes: 0

Views: 772

Answers (1)

jfriend00
jfriend00

Reputation: 707326

You have to decide up front if you want a:

  1. Temporary session for a given browser that will only work for that user in one specific browser and may be reset at any time

or

  1. A longer term session associated with a particular user that they user can use any time and from any browser.

The first can be done with a server or client generated cookie that is any globally unique value. You can then use that id as a key into your database to get the user's server-side settings/data on any given request. In node.js, there are a number of session related NPM modules that will handle the generation of a sessionID for you automatically. The problem with this first method is that it relies on the preservation of a cookie value in the user's browser. Not only can cookies be temporal (they can be cleared), but they are only set in one specific browser.

If you're only planning on using it for the duration of one session, then this first method should work just fine. It is common to use a time value (e.g. Date.now()) combined with a random number for a unique id. Since no two requests can be processed in the same ms, this guarantees a unique id value. Add the random number to make it not be predictable. Other NPM session modules offer further features such as an encryption key, etc...

The second method requires some sort of identifier that the user must enter in order to know which user it is (often an email address). If you don't want other people to be able to impersonate a user by only knowing their user id, then you also need to require a password. This essentially requires a sign-up process on your site where the user ends up with a userID and password that they use to login to your site.


It is not uncommon to see the first method used for short term storage on behalf of the user. For example, a shopping cart on a site that you are not registered for.

The second method is used by all the sites that have a user login.

Upvotes: 3

Related Questions