server-cli-only

0.3.2 · active · verified Sun Apr 19

The `server-cli-only` package, currently at version 0.3.2, acts as a build-time failsafe to prevent specific modules from being bundled into client-side (browser) code. Its primary function is to restrict imports of designated modules exclusively to server-side environments such as React Server Components, Node.js, Bun, Deno, and various edge runtimes (Vercel, Netlify, Cloudflare). Unlike the `server-only` package, which strictly targets the 'react-server' runtime, `server-cli-only` expands its allowed runtimes to encompass a broader range of server and CLI execution environments, including those defined by WinterCG specifications. This ensures sensitive code or data remains server-side, throwing build-time errors if inadvertently imported into a browser context or an unknown runtime, thereby preventing potential security vulnerabilities and unexpected client behavior. The package maintains a stable, low-frequency release cadence as it primarily focuses on a core, foundational restriction mechanism.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `server-cli-only` to restrict a module containing sensitive configuration to server/CLI environments, preventing client-side leakage.

import "server-cli-only"; // This line prevents the module from being bundled into browser code

interface SensitiveConfig {
  apiKey: string;
  databaseUrl: string;
}

export function getSensitiveConfig(): SensitiveConfig {
  // In a real application, fetch from environment variables or a secure store
  return {
    apiKey: process.env.MY_API_KEY ?? 'sk_test_123',
    databaseUrl: process.env.DATABASE_URL ?? 'mongodb://localhost:27017/mydb',
  };
}

// Example usage for a server or CLI script:
// If this file is executed directly via Node.js, Bun, or Deno:
// e.g., `ts-node src/server-logic.ts`
if (typeof process !== 'undefined' && process.argv[1] === require.main?.filename) {
  console.log("Executing server-side logic directly via CLI.");
  const config = getSensitiveConfig();
  console.log("Retrieved API Key (first 5 chars):", config.apiKey.substring(0, 5) + '...');
  console.log("Database URL:", config.databaseUrl);
}
// If imported into a React Server Component, it would execute there.
// If imported into a React Client Component, it would throw a build error.

view raw JSON →