0

I'm using JWT's for user authentication on my e-commerce website. Once a user successfully logs in, I'm sending them a JWT which is stored in the browser's localstorage.

Once the client has the JWT, I'm trying to figure out the best (or a standardized) way for the client to fetch certain data for that user? This data includes their shopping cart, wishlist, order history, etc. I can think of a few possible solutions:

  1. Include all data in the JWT. This is probably the wrong approach. Seems like only data such as user_id, phone_number, and email_address should be stored in a JWT (source).

  2. Allow the client to parse a user_id (e.g. 75) from the JWT. Client then hits /users/75 (JWT required for authentication) to fetch the user's data. However, this seems redundant because both the endpoint and the JWT point to the user.

  3. Create some endpoints like /user/shopping_cart and /user/wishlist for the client to hit (JWT required for authentication). The backend will determine which user is making the request based on the JWT. This seems like the better option.

I would bet option 3 is the best approach?

Johnny Metz
  • 5,977
  • 18
  • 82
  • 146

2 Answers2

0

storing some info like basket items can be done either in client side or back end, as you said you can save info and fetch them by user id, but some info can like shopping cart can be stored in localstorage to, in back end fetching speed is matter, i suggest using redis for stuff like simple info in back end.

0

Approach 1, Storing everything in JWT:

every time user update their cart or wishlist you have to generate a new JWT and return it to user. You wouldn't want to generate a new token on every action(add/update/delete) done by the user. Although you can encode data in JWT for initial data loading.

Approach 2, return everything with a single request

This approach is good for smaller amount of data and data that are interrelated to each other. For eg in some cases, you might want to show # num of items in cart, num of wishlist items, total orders they have made on a single page. In that case, you can make something like /dashboard which returns basic information about the user.

GET: /dashobard
{
  wishlists: 5,
  totalOrders: 100,
  cartItems: 10,
}

Approach 3

I would go with this approach. As your application grows and a large number of people are using it, they will have multiple wishlists and multiple past order history and your application might have separate pages to show that information. In that case, having a separate route for each resource is a good idea.

GET: /users/1/wishlists/  --> get all wishlist of user 1
DELETE/UPDATE: /users/1/wishlists/10/ --> update wishlist with id 10 of user 1

GET: /users/1/orders --> get all orders of user 1

You can combine all the approaches and use accordingly

Naresh
  • 941
  • 9
  • 22