How to create a cart

Updated Last: 5th March, 2024

How is a cart session handled?

A normal LAMP stack WordPress site, WooCommerce uses PHP sessions in the browser to keep shopping carts in sync and stores the session and cart data in cookies for each visitor to the site.

This stores the customers unique cart key, the cart’s expiration timestamp and when the cart will expire if not updated since.

However, when using a modern framework like React, there are no use of cookie management unless an additional module is used to support it.

How does one create a cart?

A cart is only created once the first product is added to it. Once that cart is created, a session is created in the database to save the cart information.

The session remains in an active state for a period of time and when updated, the sessions expiration is also updated.

CoCart supports both registered and guest customers. Registered customers are authenticated with their login details when a cart endpoint is used. This assigns the session to that user and doesn’t need identifying via the REST API any further.

For guest customers however, since we are making a cart endpoint request without authentication, we need to identify the cart session and in order to do that, you need to fetch and store the cart key provided from the first request made when adding a product to the cart.

Not doing so will lead to several carts being created in session with no way of getting the previous cart back the next time you add a product or make a change.

How to get the cart key?

There are two ways you can get the cart key. The first is via the cart response where you see cart_key. The second is via the returned response headers. There you will need to look for CoCart-API-Cart-Key

    "cart_hash": "cd541ec1948b600728b49c198b1f4d84",
    "cart_key": "43de87a471f517c779841b08be852b26",
    "currency": {
        "currency_code": "USD",
        "currency_symbol": "$",
        "currency_minor_unit": 2,
        "currency_decimal_separator": ".",
        "currency_thousand_separator": ",",
        "currency_prefix": "$",
        "currency_suffix": ""

Example of cart response showing the cart_key listed at the top.

Once you get the cart_key, you must store it somewhere in your application. It can be:
– using a cookie
– or using localstorage
– or using a wrapper like localForage or PouchDB
– or using local database like SQLite or Hive
– or your choice based on the app you developed

Once you have captured the cart_key in your framework, you will then need to use the captured cart key for all future Cart API requests by querying it. See examples below.

curl --location --request GET '' \
curl --location --request POST ''

And that is it. Now you have access to the same cart session.