@chargebee/code-samples
A self-contained, reusable React component for displaying API code samples with syntax highlighting, language switching, and copy functionality.
Features
- Display Component: Renders pre-generated code samples with beautiful syntax highlighting
- Multi-Language: Supports 12+ languages (cURL, Node.js, Python, PHP, Ruby, Java, .NET, Go, TypeScript)
- Syntax Highlighting: Powered by Shiki
- Feature-Rich: Carousel, copy button, animations, language switcher
- Browser Export: Optimized browser API for code generation (
createCodeGenerator)
- Themeable: Configurable themes and styling
Installation
pnpm add @chargebee/code-samples
Usage
Simple Usage (Code String)
import { CodeSamples } from '@chargebee/code-samples';
import '@chargebee/code-samples/styles';
function MyPage() {
return (
<CodeSamples
codeString={`curl https://your-site.chargebee.com/api/v2/customers \\
-u test_api_key: \\
-X POST \\
-d "first_name=John&last_name=Doe"`}
language="curl"
theme="github-light"
features={{
copyButton: true,
showLineNumbers: true,
}}
/>
);
}
Multiple Pre-generated Samples
import { CodeSamples } from '@chargebee/code-samples';
import '@chargebee/code-samples/styles';
function MyPage() {
const samples = {
'curl': 'curl https://...',
'node-v3': 'const chargebee = new Chargebee({...})',
'python-v3': 'import chargebee\nchargebee.configure(...)',
};
return (
<CodeSamples
samples={samples}
initialLanguage="node-v3"
theme="github-light"
features={{
carousel: true,
copyButton: true,
showLanguageSwitcher: true,
}}
/>
);
}
Props
codeString | string | ❌ | Raw code string to display (simplest usage) |
language | string | ❌ | Language identifier (required if codeString is provided) |
samples | Record<string, string> | Array<{languageSnippets: Record<string, string>}> | ❌ | Pre-generated code samples object or array |
responseData | any | ❌ | Sample response JSON to display |
initialLanguage | string | ❌ | Initial language selection (default: first language) |
theme | string | ThemeConfig | ❌ | Shiki theme name or custom config (default: "github-dark") |
highlighter | HighlighterConfig | ❌ | Shiki highlighter configuration |
isDark | boolean | ❌ | Explicit dark mode state (auto-detects via MutationObserver if not provided) |
features | FeaturesConfig | ❌ | Feature toggles (see below) |
className | string | ❌ | Additional CSS classes |
style | React.CSSProperties | ❌ | Inline styles |
replacements | Record<string, string> | ❌ | String replacements (e.g., {"{site}": "acme"}) |
onLanguageChange | (lang: string) => void | ❌ | Language change callback |
onCopy | (code: string) => void | ❌ | Copy callback |
onSampleChange | (index: number) => void | ❌ | Sample change callback (for carousel) |
Features Config
carousel | boolean | false | Enable carousel for multiple samples |
copyButton | boolean | true | Show copy-to-clipboard button |
animations | boolean | true | Enable fade transitions |
showHeader | boolean | true | Show/hide entire header |
showLanguageSwitcher | boolean | true | Show/hide language dropdown |
showApiExplorer | boolean | false | Show "Try in API Explorer" button |
showLineNumbers | boolean | true | Show line numbers in code blocks |
title | string | "Sample Request" | Header title |
languageFilter | string[] | undefined | Show only specific languages |
onApiExplorerClick | () => void | undefined | Callback for API Explorer button |
Additional Components & Hooks
For advanced usage, you can import sub-components and hooks to build custom implementations:
Sub-Components
import {
CodeBlock,
CodeSampleHeader,
Carousel,
LanguageSwitcher
} from '@chargebee/code-samples';
<CodeBlock
code="const x = 1;"
language="typescript"
theme="github-light"
/>
Custom Hooks
import {
useSampleLoader,
useLanguageSelection
} from '@chargebee/code-samples';
function MyCustomComponent() {
const { samples, loading } = useSampleLoader({ });
const { language, setLanguage } = useLanguageSelection();
}
Constants
import {
AVAILABLE_LANGUAGES,
DEFAULT_LANGUAGE,
DEFAULT_THEME
} from '@chargebee/code-samples';
Development
pnpm install
pnpm dev
pnpm build
Architecture
- generators/: Language-specific code generators (Go, Node.js, Python, etc.)
- metadata/: OpenAPI metadata extraction
- components/: React UI components
- styles/: CSS themes and animations
Code Generation vs Display
Important: The CodeSamples component is a display component - it renders pre-generated code strings. It does NOT generate code from OpenAPI specs.
To generate code from OpenAPI specs, use the generateCodeSample or generateCodeSamples functions (see Pure Function API below), then pass the result to the component:
import { CodeSamples } from '@chargebee/code-samples';
import { generateCodeSamples } from '@chargebee/code-samples';
export async function loader() {
const samples = await generateCodeSamples({
languages: ['curl', 'node-v3', 'python-v3'],
operation: 'create_a_customer',
apiVersion: 'v2',
pcVersion: 'v2',
site: 'acme-test',
apiKey: 'test_api_key',
request: {
uri: '/customers',
method: 'POST',
params: { first_name: 'John', last_name: 'Doe', email: 'john@example.com' }
}
});
return { samples };
}
function MyPage({ samples }) {
return <CodeSamples samples={samples} />;
}
Browser Export (Client-Side Generation)
For browser environments that need to generate code dynamically, use the browser export:
import { createCodeGenerator } from '@chargebee/code-samples/browser';
const generator = createCodeGenerator({
apiVersion: 'v2',
pcVersion: 'v2',
site: 'acme-test',
apiKey: 'test_api_key',
cache: 'memory'
});
const result = await generator.generate({
language: 'curl',
operationId: 'create_a_customer',
requestSample: {
params: { first_name: 'John', last_name: 'Doe', email: 'john@example.com' }
}
});
console.log(result.code);
Note: The browser export uses bundled operation descriptors (no external fetching required) with optional memory caching.
Pure Function API (Server-Side)
For Node.js, LLMs, Deno, Bun, or server-side generation (SSG/SSR), use the pure function API:
import { generateCodeSample, generateCodeSamples } from '@chargebee/code-samples';
const result = await generateCodeSample({
language: 'node-v3',
operation: 'create_a_customer',
apiVersion: 'v2',
pcVersion: 'v2',
site: 'acme-test',
apiKey: 'test_api_key',
request: {
uri: '/customers',
method: 'POST',
params: { first_name: 'John', last_name: 'Doe', email: 'john@example.com' }
}
});
console.log(result.code);
console.log(result.language);
const allSamples = await generateCodeSamples({
languages: ['curl', 'node-v3', 'python-v3', 'java'],
operation: 'create_a_customer',
apiVersion: 'v2',
pcVersion: 'v2',
site: 'acme-test',
apiKey: 'test_api_key',
request: {
uri: '/customers',
method: 'POST',
params: { first_name: 'John', email: 'john@example.com' }
}
});
console.log(allSamples['node-v3']);
console.log(allSamples['python-v3']);
const pregenResult = await generateCodeSample({
language: 'python-v3',
samples: {
'python-v3': 'import chargebee\nchargebee.configure(...)'
}
});
Use Cases:
- LLM/AI code generation tools
- Server-side code generation (SSG/SSR)
- CLI tools and scripts
- Non-React applications
- Testing and validation
Advanced Exports
Code Generators (Server-Side)
The code generators use pre-generated operation descriptors (bundled with the package). No external OpenAPI utils dependency is required:
import { getGenerator, getSupportedLanguages, getOperation } from '@chargebee/code-samples';
const languages = getSupportedLanguages();
const generator = getGenerator('node-v3');
const operation = getOperation('v2-pcv2', 'create_a_customer');
Type Exports
import type {
CodeSamplesPropsInterface,
GenerateCodeSampleOptions,
GenerateCodeSampleResult,
Language,
ApiVersion,
OperationDescriptor
} from '@chargebee/code-samples';
Helper Components
import {
GoToApiExplorer,
TryInApiExplorer
} from '@chargebee/code-samples';
License
Chargebee Proprietary - See LICENSE for details.