Using Headless Woo commerce store api v1 in nextjs : issue faced and solutions

RMAG news

Must read note:
_If you want only solution scroll directly to solution section

The blog is about the integrating WooCommerce Store API. Integrating it was very hard because the documentation was lacking. The documents looked simple but didn’t have enough information. This blog talks about integrating WooCommerce with a Headless API for Nextjs or React applications, but it can be used for other client-side applications too.

Issue: Nonce
The first problem was I didn’t know what a nonce was. WordPress uses a nonce to make requests more secure. At first, I didn’t know what it was. After researching for a while, I found out it was for security purposes. The documentation said the nonce should be retrieved using a PSP code in function.pho. However, they didn’t mention the function.psb part clearly. They only provided the code to generate the token, which frustrated me because there wasn’t enough information.

After deep research on how to generate the nonce, I created an endpoint to generate it. Then, I faced another issue. It wasn’t about the nonce this time; it was about something else. They were using a nonce from the cart list API, and I was shocked to find out that I had created a separate route for something already present in the cart list API.

Solution: nonce was present in cart items api

Issue: Cart Token
I found a problem with the user trying to add items to the cart multiple times. The user wanted the cart to merge when they logged in. They provided a workflow example, and I noticed a cart token in the response error. I decoded it and found it stored the user ID and some other minor details, but nothing important, so I ignored it.

After not finding anything helpful, I dug into the source code and implementation. After a long time, I discovered that only two headers were allowed: the cart token and nonce. I realized the cart token was used in previous issues. So, I tried using the JWT token from the response header in our application, and it worked.

If this had been mentioned in the documentation, it would have been easier for me. I wouldn’t have had to change anything or copy and paste so much code from chart.jwt into function.php. Although we didn’t need to alter WordPress at first, due to the complexity, I had to. In the end, though, the API was simple and easy to use.

*Solution: first use add to cart api, get the cart-token from response header using a separate api you have to use SSR to catch cart-token.
Use express server / i am using nextjs api for this. *

Issue payment

Coming soon

Please follow and like us:
Pin Share