1

I want to create a shopping cart with Meteor that allows non-logged in visitors to have persistent shopping carts.

As far as I can tell, the only way to track a non-logged in visitor in Meteor is to set a persistent ID on the client (localStorage) then pass that ID in every subscribe and method call.

Most web frameworks store a unique session ID in a cookie and that cookie is sent with every request to the server so the server always has a way to identify the visitor who sent the request - why not have similar functionality in Meteor?

It looks like Meteor persists the userId (if logged in) in localStorage and sends that userId to the server over the DDP connection - but that only helps when users are logged in. Why isn't this done with all visitors via a sessionId?

Am I missing something here? Other techniques are welcome - I just want to clean up my code and not have to pass the sessionId around everywhere.

rbwsam
  • 28
  • 4
  • You right meteor dont support cookies you can read more http://info.meteor.com/blog/session-cookies in here, you can use `local storage` for save any information you need. – ncubica Jul 23 '15 at 21:28
  • Thanks, that link explains why it hasn't been implemented even with localStorage tokens. Maybe storing carts in localStorage makes the most sense - although I really wanted to have carts tracked server-side so I could easily gather data about abandoned carts. – rbwsam Jul 23 '15 at 21:38
  • Maybe use `new Mongo.ObjectID()` to generate an id, save it inside a session variable and then use a document inside a Mongo collection to save all the data inside. Tread carefully tough, it would probably be best to use a method to manipulate that data. That way you can put in place appropriate security measures. – halbgut Jul 23 '15 at 21:49

2 Answers2

0

I'm guessing the cart is a field in your user collection schema.

Instead, make Cart its own collection and have userID be the foreign key.

Then, if the user isn't logged in, you can use the localStorage token as the ID: localStorage.getItem('Meteor.loginToken').

Finally, when the user signs up, in your createUser callback, you search for a cart with that token. If it exists, update it to the new userId.

This is also a little faster for analytics since you don't have to traverse the entire user collection to get the cart object.

Matt K
  • 4,813
  • 4
  • 22
  • 35
0

You right meteor dont support cookies you can read more http://info.meteor.com/blog/session-cookies in here, my suggestion use local storage to persist clients without login. Also take a look to how to create UUID in javascript Create GUID / UUID in JavaScript?

//I commented first and post it here since I think this is the answer my two cents.

Community
  • 1
  • 1
ncubica
  • 8,169
  • 9
  • 54
  • 72