Fixing 404 Errors When Updating Wishlist in Strapi

  Introduction

Strapi is a powerful headless CMS that makes it easy to manage and query data through REST APIs. However, when working with Many-to-Many relationships, such as wishlists containing multiple products, developers often encounter issues when trying to update existing entries.

A common error is:

PUT http://localhost:1337/api/wishlists/43 404 (Not Found)

This article explains why this happens and how to properly structure API requests to update wishlists (or similar Many-to-Many relations) in Strapi without issues.


Understanding the Problem

Why Does PUT Return a 404 Error?

  1. Strapi Uses documentId, Not Just id

    • Unlike standard relational databases, Strapi assigns a documentId to each entry.

    • Directly using PUT /api/wishlists/:id may fail because Strapi expects the documentId.

  2. Many-to-Many Relationships Need Proper Formatting

    • When updating a wishlist, you need to send the full list of associated products to prevent Strapi from overwriting existing relations.

  3. Permissions in Strapi May Block Updates

    • If the role settings do not allow PUT operations, the request might get rejected.

    • Go to Strapi Admin → Settings → Roles & Permissions and ensure updates are allowed for wishlists.

  4. Strapi's REST API Follows a Specific Update Pattern

    • Unlike traditional REST APIs, Strapi requires updates to include all related fields even if you're only modifying one.

    • If products is a Many-to-Many relation, failing to include the full array could erase existing products.


Step-by-Step Solution

 Fetch the Existing Wishlist

Before updating a wishlist, you need to retrieve the existing entry with all related products:

const fetchWishlist = async (userId) => {
  const response = await axios.get("http://localhost:1337/api/wishlists", {
    headers: { Authorization: `Bearer ${jwt}` },
    params: {
      "filters[users_permissions_user][id][$eq]": userId,
      "populate": "products",
    },
  });
  return response.data.data[0];
}; Extract documentId and Existing Products

Once you have the wishlist, extract its documentId and current product list:

const wishlist = await fetchWishlist(user.id);
const wishlistDocumentId = wishlist.documentId; //  Use documentId
const existingProducts = wishlist.products.map(prod => ({ id: prod.id }));
 Update the Wishlist Using PUT

To add or remove products while keeping existing ones intact:

const updateWishlist = async (wishlistDocumentId, updatedProducts) => {
  await axios.put(`http://localhost:1337/api/wishlists/${wishlistDocumentId}`, {
    data: {
      users_permissions_user: user.id,
      products: updatedProducts,
    },
  }, {
    headers: { Authorization: `Bearer ${jwt}` },
  });
};

4️⃣ Adding or Removing Products

To add a product:

const newProduct = { id: 10 }; // New product to add
const updatedProducts = [...existingProducts, newProduct];
await updateWishlist(wishlistDocumentId, updatedProducts);

To remove a product:

const updatedProducts = existingProducts.filter(prod => prod.id !== 10);
await updateWishlist(wishlistDocumentId, updatedProducts);

Troubleshooting Common Errors

 404 Not Found on PUT Requests

 Ensure you are using documentId instead of id in your request.
✅ Double-check that the wishlist exists by fetching it first.
✅ Restart Strapi to clear any stale database connections.

2️⃣ 403 Forbidden or 401 Unauthorized

✅ Verify that your API request includes a valid JWT token.
✅ Check Strapi Admin → Settings → Roles & Permissions to ensure that PUT is allowed for wishlists.

3️⃣ Wishlist Updates Erase Existing Products

✅ Strapi requires sending the full list of products each time you update a Many-to-Many relation.
✅ Always fetch the existing products first and include them in your update request.

4️⃣ 500 Internal Server Error or Bad Request

✅ Ensure that your PUT request body follows the correct structure (data: { products: [...] }).
✅ Check Strapi logs (npm run develop --debug) for more detailed error messages.


Key Takeaways

✅ Use documentId instead of id when updating wishlists
✅ Always fetch and send the full list of related products
✅ Ensure Strapi permissions allow PUT requests
✅ Use populate=* in GET requests to retrieve all relations
✅ Restart Strapi if errors persist

By following these steps, you can successfully update wishlists in Strapi without encountering 404 errors. 

Post a Comment

Previous Post Next Post