OC Client Node.js

raw JSON →
4.0.2 verified Thu Apr 23 auth: no javascript

The `oc-client` package serves as a robust Node.js client for the OpenComponents micro-frontend framework, primarily facilitating server-side rendering of web components. It enables applications to consume, render, and manage distributed components from one or more registries. Key functionalities include instantiating a client with specific component versions and registry endpoints, warming up component caches, retrieving component metadata, and rendering components both individually and in batches. The current stable version is 4.0.2. The project is actively maintained and explicitly states it is under "heavy development," indicating a potentially rapid release cadence and a higher likelihood of API changes between minor versions. Its core differentiator lies in providing a streamlined way to integrate OpenComponents into Node.js applications, offering features like cache management, request header forwarding, and flexible component versioning to efficiently display dynamic content.

error ReferenceError: require is not defined
cause Attempting to use CommonJS `require()` syntax (e.g., `const Client = require('oc-client');`) in an ES Module context (e.g., in a file with `"type": "module"` in `package.json` or a `.mjs` file).
fix
Use the ES Module import syntax: import Client from 'oc-client';.
error Error making request to registry
cause The `oc-client` failed to connect to or receive a valid response from the configured OpenComponents registry, often due to an incorrect registry URL, network issues, or an unresponsive registry service.
fix
Double-check that the registries.serverRendering URL provided to the Client constructor is correct and accessible from your Node.js application. Verify network connectivity and ensure the OpenComponents registry service is running and healthy. Inspect registry logs for specific error details.
error TypeError: Cannot read properties of undefined (reading 'serverRendering')
cause The `registries` object was either not provided or was empty in the `Client` constructor options, but the client attempted to access `registries.serverRendering`, which is a mandatory configuration.
fix
Ensure the registries object is passed to the Client constructor and contains at least a serverRendering URL: new Client({ registries: { serverRendering: 'https://your-registry.com/' }, ... });.
breaking The project is explicitly labeled as 'still under heavy development' and its API is 'likely to change at any time'. This indicates that breaking changes can occur frequently even in minor or patch releases.
fix Thoroughly review release notes and test suite updates with each new version. Pin dependencies to exact versions in your `package.json` to prevent unexpected breakage (`"oc-client": "4.0.2"`).
gotcha The README states 'Node.js version: **6** required', while `package.json` for version 4.0.2 specifies `"node": ">=12"`. Always defer to the `package.json` `engines` field (`>=12`) for current compatibility. Using Node.js versions older than 12 with this package may lead to unexpected behavior or errors, despite the README's outdated advice.
fix Ensure your Node.js environment is version 12 or newer to meet the package's declared engine requirements, overriding the outdated README advice.
gotcha Missing or incorrect `registries` configuration is a common cause of errors, leading to the client being unable to fetch components. The `serverRendering` property within `registries` is mandatory for server-side operations.
fix Verify that `registries.serverRendering` is provided in the Client constructor options and points to a valid OpenComponents registry URL (e.g., `{ registries: { serverRendering: 'https://your-registry.com/' } }`).
npm install oc-client
yarn add oc-client
pnpm add oc-client

Demonstrates initializing the `oc-client` with registry and component configurations, warming up components, and rendering a single component.

const Client = require('oc-client');

const client = new Client({
  registries: { serverRendering: 'https://myregistry.com/' }, // IMPORTANT: Replace with your actual OpenComponents registry URL
  components: {
    // Define components your application will consume with desired versions
    headerComponent: '1.2.3',
    footerComponent: '~2.2.5'
  },
  cache: {
    flushInterval: 60 * 5 // Optional: Cache invalidation interval in seconds (e.g., 5 minutes)
  }
});

client.init({
  // Optional: Headers to forward during component warm-up requests
  headers: {
    'accept-language': 'en-US,en;q=0.9',
    'user-agent': 'Mozilla/5.0 (Node.js) oc-client-app'
  },
  timeout: 10 // Optional: Maximum request time in seconds
}, function(error, responses){
  if (error) {
    console.error('oc-client initialization failed:', error);
    // Implement robust error handling, e.g., serve a fallback or retry
  } else {
    console.log('oc-client initialized successfully. Warm-up responses:', responses);
  }

  // Example: Render a single component
  client.renderComponent('headerComponent', {
    headers: { 'x-trace-id': 'req-123' },
    parameters: { title: 'Welcome to My App' }
  }, function(err, htmlResponse) {
    if (err) {
      console.error('Failed to render headerComponent:', err);
    } else {
      console.log('Successfully rendered headerComponent:', htmlResponse.html);
      // htmlResponse.html contains the rendered HTML string
      // htmlResponse.assets contains client-side assets (CSS, JS) if any
    }
  });
});