### Install and Run Beefree React Demo
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/INDEX.md
Steps to set up and run the Beefree React Demo application, including installing dependencies, configuring environment variables, and starting the frontend and proxy server.
```bash
# 1. Setup
npm install
cp .env.example .env
# Edit .env with your Beefree credentials
# 2. Terminal 1 - Frontend
npm run dev
# Serves on http://localhost:5173
# 3. Terminal 2 - Proxy Server
npm run proxy
# Serves on http://localhost:3001
```
--------------------------------
### Shell Command Example
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/README.md
Demonstrates a common shell command for starting a development server, often used in project setup and execution.
```bash
# Shell commands
npm run dev
```
--------------------------------
### Start Frontend Development Server
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/usage-examples.md
Run the frontend development server using npm. This command starts the Vite development server.
```bash
npm run dev
```
--------------------------------
### Start Proxy Server
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/proxy-server-reference.md
Starts the proxy server using Node.js. Alternatively, use the npm script for convenience.
```bash
node proxy-server.js
```
```bash
npm run proxy
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/usage-examples.md
Clone the project, install npm dependencies, and set up environment variables with your Beefree credentials.
```bash
cd beefree-react-demo
npm install
cp .env.example .env
# Edit .env and add your credentials from Beefree Developer Console
# BEE_CLIENT_ID=your_id_here
# BEE_CLIENT_SECRET=your_secret_here
```
--------------------------------
### Start Proxy Server
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/usage-examples.md
Run the proxy server using npm. This command starts a local proxy server, typically for handling API requests.
```bash
npm run proxy
```
--------------------------------
### Install Proxy Server Dependencies
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/README.md
Commands to install the necessary npm packages for the proxy server.
```bash
npm install express cors axios dotenv
node proxy-server.js
```
--------------------------------
### Install Dependencies
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/proxy-server-reference.md
Installs project dependencies using npm. Ensure Node.js and npm/yarn are installed.
```bash
npm install
```
--------------------------------
### Start Proxy Server for Editor Loading
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/INDEX.md
Command to start the proxy server, which is a prerequisite for the editor to load correctly. This is typically run in a separate terminal.
```bash
# Terminal 2
npm run proxy
```
--------------------------------
### Start Beefree SDK Initialization
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/api-reference-beefree-editor.md
Initiates the Beefree SDK's initialization process using the start() method. This method takes configuration, template data, and options, returning a promise that resolves upon successful initialization.
```typescript
BeefreeSDKInstance
.start(beeConfig, templateJson, '', { shared: false })
.then(() => {
console.log('Beefree SDK initialized successfully');
})
.catch((err: unknown) => {
console.error('Error during start():', err);
});
```
--------------------------------
### Start Proxy Server
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/proxy-server-reference.md
Starts the proxy server and logs a startup message. The server listens on a port defined by the PORT environment variable or defaults to 3001.
```javascript
app.listen(PORT, () => {
console.log(`Proxy server running on http://localhost:${PORT}`);
});
```
--------------------------------
### JavaScript Node.js Endpoint Example
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/README.md
Shows a JavaScript example for setting up a POST endpoint in a Node.js environment, typically for a proxy server.
```javascript
// JavaScript (for Node.js/proxy server)
app.post('/endpoint', (req, res) => { });
```
--------------------------------
### Initialize Beefree SDK
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/INDEX.md
Configure and start the Beefree SDK instance with provided configuration, template, and callbacks. Ensure the container ID matches your DOM element.
```typescript
const beeConfig = {
container: 'beefree-react-demo', // DOM element ID
language: 'en-US', // UI language
onSave: (json, html, amp, version, lang) => {}, // Save callback
onError: (error) => {} // Error callback
};
BeefreeSDKInstance.start(beeConfig, templateJson, '', { shared: false })
```
--------------------------------
### Log Server Startup
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/proxy-server-reference.md
Logs a message to the console indicating the proxy server has started and is running on a specific port.
```javascript
console.log(`Proxy server running on http://localhost:${PORT}`);
```
--------------------------------
### BeefreeSDK Initialization
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/api-reference-beefree-editor.md
Initializes the BeeFree SDK with an authentication token and starts the editor with configuration and an optional template.
```APIDOC
## BeefreeSDK Initialization
### Constructor Call
```typescript
const BeefreeSDKInstance = new BeefreeSDK(v2Token)
```
#### Parameters
- **v2Token** (object) - Required - Authentication token from proxy endpoint with `v2: true` flag
### start() Method Chain
```typescript
BeefreeSDKInstance
.start(beeConfig, templateJson, '', { shared: false })
.then(() => {
console.log('Beefree SDK initialized successfully');
})
.catch((err: unknown) => {
console.error('Error during start():', err);
});
```
#### Parameters to `.start()`
1. **beeConfig** (object) - Required - Configuration object
2. **templateJson** (object | undefined) - Optional - Pre-loaded email template
3. `''` (string) - Unused - Historical parameter, currently unused
4. **options** (object) - Required - Options object with `shared` flag set to false
#### Returns
Promise that resolves when editor fully initializes
```
--------------------------------
### Development Commands for Beefree SDK React Demo
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/project-overview.md
Run these commands in separate terminals to start the frontend and the proxy server during development. Ensure your environment variables are set.
```bash
# Terminal 1: Frontend
npm run dev
# Terminal 2: Proxy Server
npm run proxy
```
--------------------------------
### Start Vite Dev Server
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/project-overview.md
Starts the Vite development server for the frontend application. This command is typically used during development to enable hot module replacement and other development features.
```bash
vite
```
--------------------------------
### Initialize Express Server and Load Environment Variables
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/proxy-server-reference.md
Sets up the basic Express application, including importing necessary modules like express, cors, axios, and dotenv. This code is essential for starting the proxy server.
```javascript
import express from 'express';
import cors from 'cors';
import axios from 'axios';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3001;
```
--------------------------------
### Example Success Response for Authentication
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/endpoints.md
This is an example of a successful JSON response from the authentication endpoint, containing the authentication token, user ID, and an authorization token.
```json
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"uid": "demo-user",
"authorizationToken": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```
--------------------------------
### Install Beefree SDK npm Package
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/README.md
Install the official Beefree SDK npm package into your React project.
```bash
npm install @beefree.io/sdk
```
--------------------------------
### Express Server Setup
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/endpoints.md
Initializes an Express server with CORS and JSON body parsing middleware. It's configured to use environment variables for the port.
```javascript
import express from 'express';
import cors from 'cors';
import axios from 'axios';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3001;
app.use(cors());
app.use(express.json());
```
--------------------------------
### Usage Context in main.tsx
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/api-reference-app.md
Example of how the App component is imported and rendered in the application's entry point (src/main.tsx).
```tsx
// src/main.tsx
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
,
)
```
--------------------------------
### Start Express Authentication Proxy
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/project-overview.md
Launches the Express-based authentication proxy server. This server handles client credentials for the V2 authentication endpoint.
```bash
node proxy-server.js
```
--------------------------------
### Start BeefreeSDK with Configuration
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/configuration.md
Initiates the Beefree editor with specified configuration and an optional template. The 'shared' option in the config object controls shared editing mode.
```typescript
BeefreeSDKInstance.start(beeConfig, templateJson, '', { shared: false })
.then(() => { ... })
.catch((err) => { ... });
```
--------------------------------
### Deprecated Client-Side Authentication Example
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/README.md
This example demonstrates an outdated and insecure method of client-side authentication using axios. It exposes secrets directly in the client-side code and should not be used.
```typescript
// ❌ DEPRECATED EXAMPLES
// Client-side auth (no proxy)
const token = await axios.post('https://auth.getbee.io/loginV2', {
client_id: 'public-id', // Exposes secrets!
});
```
--------------------------------
### TypeScript Function Example
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/README.md
Illustrates a basic TypeScript function with syntax highlighting. Used for demonstrating TypeScript code within documentation.
```typescript
// TypeScript with syntax highlighting
function example() { }
```
--------------------------------
### Deprecated Missing Container Ref Example
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/README.md
This example illustrates a common issue where a container element for the Beefree SDK is missing a stable DOM reference, which can lead to rendering failures. Ensure a ref is attached to the container.
```jsx
// ❌ Missing container ref
// Fails: No stable DOM reference
```
--------------------------------
### Make Authentication Request via Proxy (JavaScript)
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/usage-examples.md
Example of making a POST request to the proxy server's authentication endpoint from a JavaScript/React application. Requires the 'fetch' API.
```typescript
const response = await fetch('http://localhost:3001/proxy/bee-auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ uid: 'user-123' })
});
const token = await response.json();
console.log(token);
```
--------------------------------
### Deprecated Class Component Initialization
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/README.md
This example shows an outdated pattern of initializing the Beefree SDK within a React class component's componentDidMount lifecycle method. Functional components with hooks are preferred.
```typescript
// ❌ Class component approach
class BeefreeEditor extends React.Component {
componentDidMount() {
// Avoid - outdated pattern
}
}
```
--------------------------------
### React Component for Beefree SDK Integration
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/README.md
This React component initializes and embeds the Beefree SDK. It uses `useEffect` to fetch a token from the proxy server and then starts the editor. The editor is rendered in a div with specific styling. Ensure the container ID matches the one used in the SDK configuration.
```tsx
import { useEffect, useRef } from 'react';
import BeefreeSDK from '@beefree.io/sdk';
export default function BeefreeEditor() {
const containerRef = useRef(null);
useEffect(() => {
async function initializeEditor() {
// Beefree SDK configuration
const beeConfig = {
container: 'beefree-react-demo',
language: 'en-US',
onSave: (pageJson: string, pageHtml: string, ampHtml: string | null, templateVersion: number, language: string | null) => {
console.log('Saved!', { pageJson, pageHtml, ampHtml, templateVersion, language });
},
onError: (error: unknown) => {
console.error('Error:', error);
}
};
// Get a token from your backend
const response = await fetch('http://localhost:3001/proxy/bee-auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ uid: 'demo-user' })
})
const token = await response.json();
// Initialize the editor
const bee = new BeefreeSDK(token);
bee.start(beeConfig, {});
}
initializeEditor();
}, []);
return (
);
}
```
--------------------------------
### BeefreeSDK.start()
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/configuration.md
Initializes the Beefree editor with specified configuration and an optional template. The method returns a promise that resolves when the editor is ready or rejects on error.
```APIDOC
## BeefreeSDK.start()
### Description
Initializes the Beefree editor with a configuration object, an optional template JSON, a historical parameter, and an options object. It returns a Promise that resolves on successful initialization or rejects with an error.
### Method Signature
```typescript
BeefreeSDKInstance.start(beeConfig, templateJson, '', { shared: false })
.then(() => { ... })
.catch((err) => { ... });
```
### Parameters
#### Parameter 1: beeConfig
**Type:** Configuration object
**Description:** An object containing the main configuration for the Beefree editor.
#### Parameter 2: templateJson
**Type:** object | undefined
**Description:** An optional pre-loaded email template to display in the editor. If not provided or if loading fails, the editor initializes without a template.
**Loading Logic:**
```typescript
const templateJson = await fetch('/black-friday-template.json')
.then((r) => (r.ok ? r.json() : undefined))
.catch(() => undefined);
```
#### Parameter 3: Empty String
**Type:** string
**Description:** This parameter is historical and no longer used.
#### Parameter 4: Options Object
**Type:** object
**Properties:**
- **shared** (boolean) - Optional - Defaults to `false`. Disables shared editing mode when set to `false`.
```
--------------------------------
### Using the BeefreeEditor Component
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/usage-examples.md
Demonstrates the usage of the BeefreeEditor component, which handles SDK initialization internally. No props are required.
```tsx
import BeefreeEditor from './BeefreeEditor';
function EmailBuilderPage() {
return (
Email Builder
);
}
export default EmailBuilderPage;
```
--------------------------------
### Production Build Command for Beefree SDK React Demo
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/project-overview.md
Execute this command to create an optimized production bundle for deployment. The output will be placed in the 'dist/' directory.
```bash
npm run build
```
--------------------------------
### Production Build and Preview Commands
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/INDEX.md
Commands to build the project for production and preview the built application locally. The build command optimizes assets for deployment.
```bash
npm run build # Generates optimized dist/
npm run preview # Preview production build locally
```
--------------------------------
### Initialize Beefree SDK with Constructor
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/api-reference-beefree-editor.md
Instantiates the Beefree SDK using its constructor, requiring an authentication token.
```typescript
const BeefreeSDKInstance = new BeefreeSDK(v2Token)
```
--------------------------------
### Example Internal Server Error Response
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/endpoints.md
This JSON structure represents a typical error response when an internal server error occurs during the authentication process.
```json
{
"error": "Failed to authenticate"
}
```
--------------------------------
### Preview Production Build
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/project-overview.md
Locally previews the production build of the application. This command is useful for testing the final output before deployment.
```bash
vite preview
```
--------------------------------
### Production Environment Variables (.env.production)
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/usage-examples.md
Set up frontend and proxy server configurations for a production environment using a .env.production file.
```env
# Frontend
VITE_BEE_AUTH_URL=https://api.example.com/auth/bee-auth
# Proxy server (not used in production - use environment variables)
BEE_CLIENT_ID=prod_abc123xyz789
BEE_CLIENT_SECRET=prod_secret_key_here
PORT=8080
```
--------------------------------
### Beefree React Demo Project File Structure
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/INDEX.md
An overview of the directory and file structure for the beefree-react-demo project.
```tree
beefree-react-demo/
├── src/
│ ├── main.tsx # React entry point
│ ├── App.tsx # Root component
│ ├── BeefreeEditor.tsx # Email editor component
│ ├── App.css # App styling
│ └── index.css # Global styles
├── public/
│ └── black-friday-template.json # Sample template
├── proxy-server.js # Express auth server
├── vite.config.ts # Build configuration
├── tsconfig.json # TypeScript config
└── package.json # Dependencies
```
--------------------------------
### Implement Custom Save Handler
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/usage-examples.md
Replace the default 'onSave' callback to handle saving editor content. This example sends the content to a '/api/emails/save' endpoint and shows notifications based on the response.
```typescript
onSave: async (pageJson, pageHtml, ampHtml, templateVersion, language) => {
// Send email to server for storage
const response = await fetch('/api/emails/save', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
json: pageJson,
html: pageHtml,
ampHtml: ampHtml,
version: templateVersion,
language: language
})
});
if (response.ok) {
const saved = await response.json();
console.log('Email saved with ID:', saved.id);
showNotification('Email saved successfully!');
} else {
showNotification('Error saving email');
}
}
```
--------------------------------
### TypeScript Ambient Module Declaration
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/module-exports.md
This ambient module declaration file provides type information for Vite client-side modules. It's a standard setup for Vite projects using TypeScript.
```typescript
///
```
--------------------------------
### Resolve Port Already in Use Error
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/proxy-server-reference.md
Provides commands to kill the process using a specific port or to change the PORT environment variable if the server fails to start due to a port conflict.
```bash
kill -9 $(lsof -t -i :3001) # Kill process using port
# Or change PORT in .env
```
--------------------------------
### Implement Custom Error Handler
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/usage-examples.md
Replace the default 'onError' callback to handle editor errors. This example logs the error, sends it to an error tracking service if available, and displays a user-friendly message.
```typescript
onError: (error: unknown) => {
console.error('Editor error:', error);
// Send to error tracking service
if (window.errorTracker) {
window.errorTracker.captureException(error);
}
// Show user-friendly message
if (error instanceof Error) {
showNotification(`Error: ${error.message}`);
} else {
showNotification('An unknown error occurred in the editor');
}
}
```
--------------------------------
### Create React App with TypeScript
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/README.md
Use npm to create a new React application with the TypeScript template. Navigate into the newly created project directory.
```bash
npm create vite@latest beefree-react-demo -- --template react-ts
cd beefree-react-demo
```
--------------------------------
### Debug SDK Initialization
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/usage-examples.md
Initializes the Beefree SDK, fetching a template and authentication token. Logs progress and timing for debugging the initialization process. Ensure VITE_BEE_AUTH_URL is set or use the default.
```typescript
useEffect(() => {
async function initializeEditor() {
try {
console.time('SDK Init');
const templateJson = await fetch('/black-friday-template.json')
.then((r) => (r.ok ? r.json() : undefined))
.catch(() => undefined);
console.log('Template loaded:', !!templateJson);
const response = await fetch(
import.meta.env.VITE_BEE_AUTH_URL || 'http://localhost:3001/proxy/bee-auth',
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ uid: 'demo-user' })
}
);
console.log('Auth response status:', response.status);
const token = await response.json();
console.log('Token received:', !!token.token);
const v2Token = { ...token, v2: true };
const BeefreeSDKInstance = new BeefreeSDK(v2Token);
await BeefreeSDKInstance
.start(beeConfig, templateJson, '', { shared: false });
console.timeEnd('SDK Init');
console.log('Beefree SDK initialized successfully');
} catch (error) {
console.error('Initialization error:', error);
}
}
initializeEditor();
}, []);
```
--------------------------------
### Development Environment Variables (.env)
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/usage-examples.md
Configure frontend and proxy server settings for local development using a .env file.
```env
# Frontend
VITE_BEE_AUTH_URL=http://localhost:3001/proxy/bee-auth
# Proxy server
PORT=3001
BEE_CLIENT_ID=dev_abc123xyz789
BEE_CLIENT_SECRET=dev_secret_key_here
```
--------------------------------
### List Document Files
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/MANIFEST.md
Lists the generated markdown files in the output directory with their sizes. Useful for verifying that documentation files have been created.
```bash
ls -lh /workspace/home/output/
```
--------------------------------
### Resolve Port Conflict for Proxy Server
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/INDEX.md
Command to forcefully terminate the process using port 3001, typically used when the proxy server fails to start due to the port already being in use. Alternatively, the port can be changed in the .env file.
```bash
# Change PORT in .env, or:
kill -9 $(lsof -t -i :3001)
```
--------------------------------
### Development Server Commands
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/INDEX.md
Commands to run the frontend development server and the proxy server. The frontend runs on port 5173 and the proxy on port 3001.
```bash
npm run dev # Frontend on port 5173
npm run proxy # Proxy server on port 3001
```
--------------------------------
### Build Project
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/project-overview.md
Compiles TypeScript code and builds the production-ready bundle using Vite. This command is used before deploying the application.
```bash
tsc -b && vite build
```
--------------------------------
### Environment Variables for Beefree SDK Credentials
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/README.md
This file should contain your Beefree SDK client ID and client secret. Replace 'YOUR-CLIENT-ID' and 'YOUR-CLIENT-SECRET' with your actual credentials obtained from Beefree.
```env
BEE_CLIENT_ID='YOUR-CLIENT-ID'
BEE_CLIENT_SECRET='YOUR-CLIENT-SECRET'
```
--------------------------------
### DocsButton Component
Source: https://github.com/beefreesdk/beefree-react-demo/blob/main/_autodocs/api-reference-app.md
Renders an external documentation link button, providing a quick reference to the Beefree SDK documentation.
```APIDOC
## DocsButton Component
### Description
Renders an external documentation link button.
### Component Signature
```tsx
function DocsButton(): JSX.Element
```
### Return Value
JSX with:
- `` tag linking to `https://docs.beefree.io/beefree-sdk`
- `target="_blank"` opens in new tab
- `rel="noopener noreferrer"` security attributes
- `