Client-Side Module Marker

0.0.1 · active · verified Tue Apr 21

The `client-only` package is a specialized marker module within the React Server Components (RSC) ecosystem, primarily used in frameworks like Next.js App Router. Its sole purpose is to indicate to the build system that a module and all its transitive dependencies are intended exclusively for client-side execution. It doesn't export any functions or values, acting purely as a side-effect import. When a module imports `client-only`, compatible bundlers and frameworks will enforce that this module is never included in a server bundle, providing build-time errors for misuse. This package, currently at version `0.0.1` and infrequently updated due to its static nature, complements `server-only` to clearly define server-client boundaries in a hybrid rendering environment. Its key differentiator is its explicit, declarative way of preventing accidental server-side imports of client-specific code, which helps avoid issues like 'window is not defined' errors during server rendering.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates a simple React Client Component that explicitly imports `client-only` to ensure it only runs in client environments and uses browser-specific APIs.

import 'client-only';
import { useState, useEffect } from 'react';

export default function ClientSideCounter() {
  // This component will only run on the client, enforced by 'client-only'
  const [count, setCount] = useState(0);
  const [isBrowser, setIsBrowser] = useState(false);

  useEffect(() => {
    setIsBrowser(typeof window !== 'undefined');
    // Example of browser-specific API usage
    if (isBrowser) {
      console.log('Running on browser. User agent:', window.navigator.userAgent);
    }
  }, [isBrowser]);

  return (
    <div>
      {isBrowser ? (
        <p>You clicked {count} times</p>
      ) : (
        <p>Loading client component...</p>
      )}
      <button onClick={() => setCount(count + 1)}>Click me</button>
      {!isBrowser && <p>This component is client-only and will hydrate soon.</p>}
    </div>
  );
}

view raw JSON →