Reading list Switch to dark mode

    How to create a Product page using CS-Cart API in NextJs

    Updated 18 September 2023

    How to use Next.JS with Cs-cart – Hello Guys, Today in this blog we will see all about the API integration in the cs-cart product detail page with the next js so hope this blog will be interactive for you so let’s get started.

    CS-Cart Overview: CS-Cart is a popular e-commerce platform that allows businesses to create and manage online stores.

    One of the key strengths of CS-Cart is its flexibility, which includes an API that enables developers to extend and customize the platform’s functionality.

    Creating a Product Page Using CS-Cart API in Next.js:

    In this comprehensive guide, we will explore how to create a product page using CS-Cart API in a Next.js application.

    Start your headless eCommerce
    now.
    Read More

    For CSS design if you want to make a good user interface you can choose your desired Dependencies for the design part.

    We will break down the process into several steps, providing code examples and explanations along the way.

    Step 1: Project Setup – In the first step you have to set up this project You can follow this setup nextjs project blog that covers all about the next js project setup.

    Step 2: Global Variable Setup – We’re going to create a file named .env in the root directory and add the following code.

    //------------.env--------------//
    apiUrl: 'YOUR_CS_CART_API_URL_HERE',
    apiKey:'YOUR_API_KEY_HERE'
    anayze:true

    Again we also need to define the environment variables in our next.config.js file otherwise we will not be able to use these variables at the frontend.

    module.exports = withBundleAnalyzer(nextConfig);
    //------------next.config.js-----------//
    /** @type {import('next').NextConfig} */
    const path = require('path');
    const withBundleAnalyzer = require('@next/bundle-analyzer')({
      enabled: process.env.anayze === 'true',
    });
    const nextConfig = {
     env: {
     apiUrl: process.env.apiUrl, 
     apiKey: process.env.apiKey }, 
     reactStrictMode: true,
      },
      reactStrictMode: true,
    };
    module.exports = withBundleAnalyzer(nextConfig);


    Step 3: Install Dependencies – In this step, you can install all necessary species for your project In our case we just need tailwind-css for basic design.

    Step 4. API Response – below mentioned image demonstrates the cs-card ‘s product detail page’s API response

    postman__api_response-1-1

    Step 5: Create a Component for the Product Page – Inside the pages directory of your Next.js project, create a new folder called product and under it [urlkey].js for the dynamic route, This file will contain the code for your product detail page & component.

    //---------------pages/product/[urlkey].js-----------//
    import React, { useEffect, useState } from "react";
    import {useRouter} from "next/router"
    export default function ProductPage() {
      const router = useRouter
      const [isLoading, setLoading] = useState(true);
      const [data, setData] = useState(null);
      const id = router.query.urlkey
      useEffect(() => {
        const apiUrl = process.env.apiUrl+`api/productDetails/${id};
        const apiKey = process.env.apiKey;
    
        fetch(apiUrl, {
          headers: {
            Authorization: `Bearer ${apiKey}`,
          },
        })
          .then((response) => {
            setLoading(false);
            setData(json.response(response.data));
          })
          .catch((error) => {
            console.error("Error fetching product data:", error);
            setLoading(false);
            setData(null);
          });
      }, []);
    
      const ProdcutDetail = (props) => {
        const data = props?.props || null;
        return (
          <React.Fragment>
            <div className="mt-6">
              <div classname="lg:px-24 md:px-12 px-3">
                <div className="container mx-auto px-4">
                  <div className="lg:col-gap-12 xl:col-gap-16 mt-3 grid grid-cols-1 gap-12 lg:mt-12 lg:grid-cols-5 lg:gap-16">
                    <div className="lg:col-span-3 lg:row-end-1">
                      <div className="lg:order-2 ">
                        <div className="max-w-xl overflow-hidden rounded-lg">
                          <Image
                            className="h-[70vh]"
                            src={data?.main_pair?.main}
                            width={500}
                            height={230}
                            priority={true}
                            alt="loading"
                          />
                        </div>
                      </div>
                    </div>
                    <div className="lg:col-span-4 lg:row-span-2 lg:row-end-2">
                      <h1 className="sm: text-2xl font-bold text-gray-900 sm:text-3xl">
                        {data?.product}
                      </h1>
                      <div className=" mt-3">
                        <p className=" text-sm font-medium text-gray-500">
                          In Stock : {data?.max_qty}
                        </p>
                      </div>
                      <h2 className="mt-3 text-base text-gray-900">Details </h2>
                      <div className="mt-3  flex select-none flex-wrap items-center gap-1">
                        <section>
                          <p
                            dangerouslySetInnerHTML={{
                              __html: data?.full_description,
                            }}
                          ></p>
                        </section>
                      </div>
    
                      <div className="mt-10 flex flex-col items-center justify-between space-y-4 border-t border-b py-4 sm:flex-row sm:space-y-0">
                        <div className="flex items-end">
                          <h1 className="text-3xl font-bold">
                            ${parseFloat(data.price)}
                          </h1>
                        </div>
                        <button
                          type="button"
                          className="inline-flex items-center justify-center rounded-md border-2 border-transparent bg-gray-900 bg-none px-12 py-3 text-center text-base font-bold text-white transition-all duration-200 ease-in-out focus:shadow hover:bg-gray-800"
                        >
                          <svg
                            xmlns="http://www.w3.org/2000/svg"
                            className="shrink-0 mr-3 h-5 w-5"
                            fill="none"
                            viewBox="0 0 24 24"
                            stroke="currentColor"
                            strokeWidth={2}
                          >
                            <path
                              strokeLinecap="round"
                              strokeLinejoin="round"
                              d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"
                            />
                          </svg>
                          Add to cart
                        </button>
                      </div>
                      <ul className="mt-8 space-y-2">
                        <li className="flex items-center text-left text-sm font-medium text-gray-600">
                          <svg
                            className="mr-2 block h-5 w-5 align-middle text-gray-500"
                            xmlns="http://www.w3.org/2000/svg"
                            fill="none"
                            viewBox="0 0 24 24"
                            stroke="currentColor"
                          >
                            <path
                              strokeLinecap="round"
                              strokeLinejoin="round"
                              strokeWidth={2}
                              d="M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0 2 2 0 012-2h1.064M15 20.488V18a2 2 0 012-2h3.064M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                              className
                            />
                          </svg>
                          Free shipping worldwide
                        </li>
                        <li className="flex items-center text-left text-sm font-medium text-gray-600">
                          <svg
                            className="mr-2 block h-5 w-5 align-middle text-gray-500"
                            xmlns="http://www.w3.org/2000/svg"
                            fill="none"
                            viewBox="0 0 24 24"
                            stroke="currentColor"
                          >
                            <path
                              strokeLinecap="round"
                              strokeLinejoin="round"
                              strokeWidth={2}
                              d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"
                              className
                            />
                          </svg>
                          Cancel Anytime
                        </li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </React.Fragment>
        );
      };
      
      return (
        <div>
          {isLoading ? (
            "Loading"
          ) : data ? (
            <React.Fragment>
              <ProdcutDetail props={data} />
            </React.Fragment>
          ) : (
            "No data available"
          )}
        </div>
      );
    }

    Output will look like the below image

    sc-cart-wenkul-output

    In this code:

    • We have used tailwind-css for ProdcutDetail styling the product detail component.
    • We display the product information once it’s loaded.

    Step 6: Configure API Authentication – To access the CS-Cart API, you will need to configure authentication. Typically, CS-Cart uses API tokens or OAuth 2.0 for authentication.

    Consult your CS-Cart API documentation or settings to obtain the necessary authentication credentials.

    Once you have the credentials, you can modify the fetch request in useEffect to include authentication headers:

    //---------------pages/product/[urlkey].js-----------//
    useEffect(() => {
      const apiUrl = process.env.apiUrl;
      const apiKey = process.env.apiKey;
      fetch(apiUrl, {
        headers: {
          Authorization: `Bearer ${apiToken}`,
    // whatever you you 'll get the token in base64 (usermail:apikey)
        },
      })
        .then((response) => {
          setProduct(response.data);
        })
        .catch((error) => {
          console.error('Error fetching product data:', error);
        });
    }, []);

    Step 7: Running Your Next.js Application To see your product page in action, run your Next.js application:

    npm run dev

    This command will start the development server, and you can access your site at You can see the  http://localhost:3000

    Conclusion: In this guide, we’ve created a product page in a Next.js application that fetches product data from the CS-Cart API.

    We covered setting up the development environment, creating a component, configuring API authentication, styling and routing.

    By following these steps and customizing them to your specific CS-Cart store and design requirements, you can create a dynamic and interactive product page that integrates seamlessly with your CS-Cart e-commerce platform.

    Start your Cs-cart Headless Development with Webkul.

    Happy Coding !!

    . . .
    Discuss on Helpdesk

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home