Deviopath › Next.js

Detect "use client"

Easy · Client Components

The "use client" directive only works when it is the very first statement of the file, before any imports. Comments and blank lines above it are fine; a "use client" further down is just an unused string and does nothing.

Write isClientComponent(source) that returns true when the file starts with the directive:

- Skip blank lines and lines that start with // (after trimming spaces).

- The first remaining line, trimmed, must be 'use client' or "use client", optionally followed by ;.

- Otherwise return false.

Simplified: only // comments are handled, not /* */ blocks.

Next: Loading State