George Oblapenko
George Oblapenko

Reputation: 878

Setting cookies in flask vs JS

I'm writing a small web-store, The backend is written in Flask, and I'm using jQuery to display popups, filter some inputs, etc.

There's a very simple cart, and I've ran into one question while making it. I was thinking of storing the id's of each product selected (along with the amount) in cookies, and to generate the 'cart' part of the page via JS by accessing them. Currently, I'm setting the cookies by POSTing an AJAX call to the server, which then updates the cookies.

Javascript:

$('#addcart_' + this_id).click(function() {
  $.ajax({
    type: "POST",
    url: '/cart/',
    data: JSON.stringify({"id": this_id, "amount": total_amt}),
    contentType: "application/json; charset=UTF-8",
    datatype: 'json',
    async: false
  });
});

And in Flask:

@app.route('/cart/', methods=["POST"])
def cart_update():
    if request.method == "POST":
        data = request.get_json()
        # more code
    return resp  # response with cookies

Now, I was wondering, is there any point in actually doing that? I just need to store some data in cookies, and doing a call to Flask doesn't seem to add anything, so perhaps I could just set them via JS and live happily ever after? Or are there some downsides?

Upvotes: 2

Views: 1535

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 159905

There is absolutely no need to make a server-side call to set the selected products cookie. Updating it on the client side is much preferred, as it takes out all of the latency from the transaction.

Another thing to consider though is that your cookie will be sent along with every server-bound request. If you don't need this behavior (and you are fine with the browser support for it) you can use localStorage and only send back the selected values when the user checks out.

Upvotes: 3

Related Questions