RSC Environment Discriminator

0.0.2 · active · verified Tue Apr 21

rsc-env is a focused utility package designed to provide a reliable method for discriminating between React Server Component (RSC) and other JavaScript environments (e.g., client components, traditional server-side rendering). It achieves this by leveraging export conditions, a modern module feature that allows bundlers to statically determine the correct environment at build time. This enables aggressive tree-shaking, ensuring that server-only logic is entirely removed from client bundles, thereby optimizing bundle size and improving application performance. The package is currently in its early stages, at version 0.0.2, and its release cadence is expected to align with the evolving React Server Components ecosystem. A key differentiator for rsc-env is its targeted approach to the `react-server` condition, offering a more robust and future-proof solution for conditional code execution in modern React applications, especially those built with frameworks like Next.js App Router, compared to heuristic-based methods (e.g., checking for `useEffect` presence). This explicit approach ensures bundler compatibility and optimal performance.

Common errors

Warnings

Install

Imports

Quickstart

This code demonstrates how `rsc-env` can be used within a shared utility function and component to conditionally execute or include code based on whether it's running in a React Server Component or a client component environment, leveraging static tree-shaking.

// utils/feature-toggle.ts
import { rsc } from "rsc-env";

interface FeatureConfig {
  name: string;
  enabledInServer: boolean;
  message: string;
}

const getFeatureStatus = (feature: string): FeatureConfig => {
  if (rsc) {
    // This block is only included in server component builds
    console.log(`[RSC] Checking feature '${feature}' status.`);
    return {
      name: feature,
      enabledInServer: true,
      message: `Feature '${feature}' is active on the server.`
    };
  } else {
    // This block is tree-shaken from server component builds
    console.log(`[Client] Checking feature '${feature}' status.`);
    return {
      name: feature,
      enabledInServer: false,
      message: `Feature '${feature}' is active on the client.`
    };
  }
};

// Example usage in a shared component or utility
export function MySharedComponent() {
  const status = getFeatureStatus("new-dashboard-widget");
  return (
    <div>
      <h2>Feature Status: {status.name}</h2>
      <p>{status.message}</p>
      {rsc && <p>Server-side logic: {status.enabledInServer ? 'Enabled' : 'Disabled'}</p>}
      {!rsc && <p>Client-side logic: {status.enabledInServer ? 'Enabled' : 'Disabled'}</p>}
    </div>
  );
}

view raw JSON →