ESHOPMAN

ESHOPMAN Asset Management: Conquering Server-Side File Uploads in Node.js

ESHOPMAN Asset Management: Conquering Server-Side File Uploads in Node.js

Welcome to the forefront of headless commerce, where flexibility meets robust integration. At Move My Store, we specialize in helping businesses leverage platforms like ESHOPMAN to build powerful, scalable online storefronts. ESHOPMAN stands out as a cutting-edge headless commerce solution, seamlessly integrated as a HubSpot application. It empowers merchants with intuitive storefront management directly within HubSpot and deploys high-performance storefronts using the HubSpot CMS. Built on a modern Node.js/TypeScript stack, ESHOPMAN offers both an Admin API for backend operations and a Store API for frontend interactions, providing unparalleled control over your digital commerce presence.

For developers and merchants alike, managing product assets – such as high-resolution images, videos, and other media files – is a fundamental aspect of maintaining a rich and engaging online catalog. While ESHOPMAN provides excellent tools for this, the true power often lies in automating these tasks through server-side scripts. This is where the ESHOPMAN Admin API, accessed via the ESHOPMAN JS SDK, becomes indispensable for operations like bulk imports, syncing assets from external systems, or programmatic updates.

Diagram of ESHOPMAN Node.js file upload process with polyfill
Diagram of ESHOPMAN Node.js file upload process with polyfill

The Power of ESHOPMAN's Admin API for Developers

The ESHOPMAN Admin API is the backbone for programmatic control over your commerce data. It allows developers to manage products, orders, customers, and, crucially, digital assets. For server-side applications, this means the ability to:

  • Automate Product Imports: Seamlessly bring in product data, including associated images, from ERPs or PIMs.
  • Synchronize Assets: Keep your ESHOPMAN storefront in sync with external media libraries or content management systems.
  • Batch Process Media: Efficiently upload and manage large volumes of images or other media files without manual intervention.
  • Enhance Data Integrity: Ensure all product assets are correctly linked and available across your ESHOPMAN-powered storefronts.

These capabilities are vital for any growing e-commerce business looking to scale operations and maintain data consistency across complex ecosystems.

Unveiling a Server-Side Upload Challenge: 'ReferenceError: FileList is not defined'

Despite the robust design of the ESHOPMAN Admin API and its accompanying JS SDK, a specific challenge emerged for developers attempting server-side file uploads from Node.js environments. When utilizing the SDK's sdk.admin.upload.create() function, some developers encountered a ReferenceError: FileList is not defined. This error would halt execution even before an actual request could be sent to the ESHOPMAN backend, effectively preventing the desired server-side asset management.

The root cause of this issue lies in the fundamental differences between browser environments and Node.js. The ESHOPMAN JS SDK's internal logic, specifically within its upload.ts module responsible for handling file uploads, includes a check for body instanceof FileList. While FileList is a standard global object readily available in web browsers (representing a list of files selected by a user via an element), it is not defined in the Node.js runtime. Referencing an undeclared global object in Node.js immediately triggers a ReferenceError, bringing the script to an abrupt halt.

Impact on ESHOPMAN Development Workflows

This seemingly minor technical detail had a significant impact on ESHOPMAN developers. It directly impeded critical server-side workflows that rely on automated asset management. Tasks such as:

  • Automated product image imports from external data sources.
  • Programmatic syncing of media files from a digital asset management (DAM) system.
  • Large-scale batch processing of product media updates.

All these essential operations were temporarily blocked, creating a hurdle for developers striving to build highly automated and efficient ESHOPMAN-powered commerce solutions. The ESHOPMAN Admin API is designed precisely for such server-side interactions, making this a crucial capability to restore.

Reproducing the Issue

Here's a simplified code snippet that demonstrates how the ReferenceError would manifest when attempting a file upload in a Node.js environment without the necessary adjustments:

import ESHOPMAN from "@eshopman/js-sdk";
import fs from "fs";

// Assume 'myImage.jpg' exists in the same directory
const filePath = "./myImage.jpg";

const sdk = new ESHOPMAN({
  baseUrl: "http://localhost:9000", // Replace with your ESHOPMAN Admin API base URL
  adminApiKey: "YOUR_ADMIN_API_KEY" // Replace with your actual Admin API key
});

async function uploadFile() {
  try {
    // This approach would trigger the FileList error in Node.js
    // as 'fs.readFileSync' returns a Buffer, not a browser FileList/File object.
    // The SDK's internal check for 'body instanceof FileList' would fail.
    const fileC

    // This line would cause the ReferenceError before the request is even sent
    const upload = await sdk.admin.upload.create({
      file: fileContent, // This is where the type mismatch occurs
      name: "myImage.jpg",
      mimeType: "image/jpeg"
    });
    console.log("Upload successful:", upload);
  } catch (error) {
    console.error("Error during upload:", error);
  }
}

uploadFile();

The ESHOPMAN Solution: Bridging Browser and Server Environments

To overcome the ReferenceError: FileList is not defined, the key is to provide the ESHOPMAN JS SDK with a file object that mimics the structure and properties of a browser-native File object, even when operating in a Node.js environment. This involves leveraging Node.js's capabilities to read file data and then constructing an object that satisfies the SDK's internal checks.

The solution involves using Node.js's file system module (fs) to read the file content into a Buffer, and then creating a browser-compatible File object from that Buffer. Libraries like node-fetch (which provides global Blob and File polyfills) or other dedicated polyfills can be instrumental here. By doing so, we can ensure the object passed to sdk.admin.upload.create() is recognized correctly.

Implementing the Solution in Node.js

Here’s how you can correctly upload files to ESHOPMAN from a Node.js script, bypassing the FileList issue:

import ESHOPMAN from "@eshopman/js-sdk";
import fs from "fs";
import path from "path";

// You might need to install a polyfill for Blob and File if not globally available
// For example, using 'node-fetch' which provides these globals:
// import { Blob, File } from 'node-fetch'; // Or ensure they are globally polyfilled

// For demonstration, we'll assume Blob and File are available or polyfilled.
// In a real-world scenario, you might use a library like 'form-data' or 'web-file-api'
// to create these objects reliably in Node.js.

const sdk = new ESHOPMAN({
  baseUrl: "http://localhost:9000", // Replace with your ESHOPMAN Admin API base URL
  adminApiKey: "YOUR_ADMIN_API_KEY" // Replace with your actual Admin API key
});

async function uploadFile(filePath: string, fileName: string, mimeType: string) {
  try {
    // 1. Read the file content into a Buffer
    const fileBuffer = fs.readFileSync(filePath);

    // 2. Create a Blob from the Buffer
    // In Node.js, you'd typically use a Blob polyfill or construct a FormData object.
    // For this example, we'll conceptually create a Blob and then a File.
    const fileBlob = new Blob([fileBuffer], { type: mimeType });

    // 3. Create a File object from the Blob
    // The File constructor takes (fileBits, fileName, options)
    const fileObject = new File([fileBlob], fileName, { type: mimeType });

    // 4. Pass the File object to the ESHOPMAN SDK
    const upload = await sdk.admin.upload.create({
      file: fileObject, // Now passing a browser-compatible File object
      name: fileName,
      mimeType: mimeType
    });

    console.log("Upload successful:", upload);
    return upload;
  } catch (error) {
    console.error("Error during upload:", error);
    throw error;
  }
}

// Example usage:
const imagePath = path.join(__dirname, "./product-image.jpg"); // Ensure this file exists
const imageName = "product-image.jpg";
const imageMimeType = "image/jpeg";

uploadFile(imagePath, imageName, imageMimeType)
  .then(() => console.log("File upload process completed."))
  .catch(err => console.error("Failed to upload file.", err));

By constructing a File object in this manner, we provide the ESHOPMAN SDK with the expected data type, allowing it to proceed with the upload process without encountering the ReferenceError. This approach ensures that your Node.js scripts can fully leverage the ESHOPMAN Admin API for robust server-side asset management.

Best Practices for ESHOPMAN Asset Management

Beyond resolving specific technical challenges, adopting best practices for asset management within your ESHOPMAN ecosystem is crucial for long-term success:

  • Centralized Asset Storage: While ESHOPMAN handles asset storage, consider integrating with a dedicated Digital Asset Management (DAM) system or cloud storage solutions for original, high-resolution files. ESHOPMAN can then link to these assets or store optimized versions.
  • Batch Processing with Care: When performing large batch uploads, implement rate limiting and robust error handling in your Node.js scripts to prevent overwhelming the API or encountering transient network issues.
  • Metadata and Tagging: Leverage ESHOPMAN's capabilities to add descriptive metadata, tags, and categories to your uploaded assets. This improves searchability, organization, and SEO for your HubSpot CMS-deployed storefront.
  • Image Optimization: Ensure images are optimized for web delivery (appropriate formats, compression, responsive sizes) before or during upload to enhance storefront performance and user experience.
  • Automated Cleanup: Develop scripts to identify and remove unused or outdated assets periodically, keeping your ESHOPMAN media library lean and efficient.

Conclusion

The ESHOPMAN platform offers a powerful, headless commerce experience deeply integrated with HubSpot, providing unparalleled control over your storefronts deployed via HubSpot CMS. While navigating the nuances of browser-centric SDKs in a Node.js environment can present unique challenges, understanding the underlying mechanisms allows developers to implement effective solutions.

By correctly handling file uploads through the ESHOPMAN JS SDK in Node.js, you unlock the full potential of server-side automation for asset management. This empowers you to build more efficient, scalable, and robust commerce solutions, ensuring your ESHOPMAN-powered storefronts always showcase your products with the highest quality assets. For further expertise in ESHOPMAN migrations and development, visit Move My Store – your ESHOPMAN Migration Hub.

Share:

Start with the tools

Explore migration tools

See options, compare methods, and pick the path that fits your store.

Explore migration tools