Beefreesdk Skill
Beefree SDK Guidelines
Guidelines and best practices for building applications with Beefree SDK, including installation, authentication, configuration, customization, and template management.
Installation Guidelines
Package Installation
Dependencies
- Beefree SDK requires the following core dependencies:
{
"dependencies": {
"@beefree.io/sdk": "^9.0.2-fix-optional-url-config.0",
"axios": "^1.10.0",
"express": "^5.1.0",
"cors": "^2.8.5",
"dotenv": "^17.2.0"
}
}
Environment Setup
Authentication Guidelines
Proxy Server Setup
ALWAYS use a proxy server for authentication to protect your credentials
Create a proxy server file (e.g., proxy-server.js) to handle authentication:
import express from 'express';
import cors from 'cors';
import axios from 'axios';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
const PORT = 3001;
app.use(cors());
app.use(express.json());
const BEE_CLIENT_ID = process.env.BEE_CLIENT_ID;
const BEE_CLIENT_SECRET = process.env.BEE_CLIENT_SECRET;
// V2 Auth Endpoint
app.post('/proxy/bee-auth', async (req, res) => {
try {
const { uid } = req.body;
const response = await axios.post(
'https://auth.getbee.io/loginV2',
{
client_id: BEE_CLIENT_ID,
client_secret: BEE_CLIENT_SECRET,
uid: uid || 'demo-user',
},
{ headers: { 'Content-Type': 'application/json' } }
);
res.json(response.data);
} catch (error) {
console.error('Auth error:', error.message);
res.status(500).json({ error: 'Failed to authenticate' });
}
});
app.listen(PORT, () => {
console.log(`Proxy server running on http://localhost:${PORT}`);
});
Authentication Process
- Use the V2 authentication endpoint:
https://auth.getbee.io/loginV2
- Pass the ENTIRE API response to the Beefree SDK, not just the token
- Example authentication call:
const token = await fetch('http://localhost:3001/proxy/bee-auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ uid: 'demo-user' }),
}).then(res => res.json());
Container Setup Guidelines
HTML Container
CSS Styling
React Container
For React applications, the following code snippet shows an example using refs to manage the container:
const containerRef = useRef<HTMLDivElement>(null);
return (
<div
id="beefree-react-demo"
ref={containerRef}
style={{
height: '600px',
width: '90%',
margin: '20px auto',
border: '1px solid #ddd',
borderRadius: '8px'
}}
/>
);
Configuration Guidelines
Required Configuration Parameters
Optional Configuration Parameters
- Customize your SDK with optional parameters:
const beeConfig = {
container: 'beefree-sdk-container', // Required
language: 'en-US',
specialLinks: [
{
type: 'unsubscribe',
label: 'Unsubscribe',
link: 'http://[unsubscribe]/',
},
{
type: 'subscribe',
label: 'Subscribe',
link: 'http://[subscribe]/',
},
],
mergeTags: [
{
name: 'First Name',
value: '[first_name]',
},
{
name: 'Last Name',
value: '[last_name]',
},
{
name: 'Email',
value: '[email]',
},
],
};
Callback Functions
- Implement essential callback functions for proper functionality:
const beeConfig = {
container: 'beefree-sdk-container',
onSave: function (jsonFile, htmlFile) {
console.log('Template saved:', jsonFile);
// Implement custom save logic here
},
onAutoSave: function (jsonFile) {
console.log('Auto-saving template...');
localStorage.setItem('email.autosave', jsonFile);
},
onSend: function (htmlFile) {
console.log('Email ready to send:', htmlFile);
// Implement custom send logic here
},
onError: function (errorMessage) {
console.error('Beefree SDK error:', errorMessage);
// Handle errors appropriately
},
};
SDK Initialization Guidelines
Basic Initialization
- Initialize the Beefree SDK with proper error handling:
async function initializeBeefree(authResponse) {
try {
const bee = new BeefreeSDK(authResponse);
bee.start(beeConfig, {});
console.log('Beefree SDK initialized successfully');
} catch (error) {
console.error('Failed to initialize Beefree SDK:', error);
}
}
React Integration
For React applications, the following code snippet shows an example using useEffect for initialization:
useEffect(() => {
async function initializeEditor() {
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);
},
};
const token = await fetch('http://localhost:3001/proxy/bee-auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ uid: 'demo-user' }),
}).then(res => res.json());
const bee = new BeefreeSDK(token);
bee.start(beeConfig, {});
}
initializeEditor();
}, []);
Template Loading Guidelines
Loading Templates
Use the start() method with template data to load existing templates:
// Load template from localStorage
const selectedTemplate = JSON.parse(localStorage.getItem('currentEmailData'));
if (selectedTemplate) {
beefreeSDKInstance.start(selectedTemplate);
console.log('Loaded template from localStorage');
} else {
// Start with empty template
beefreeSDKInstance.start();
console.log('Started with empty template');
}
Template Storage
Store templates in localStorage for persistence while testing:
// Save template data
localStorage.setItem('currentEmailData', JSON.stringify(templateData));
localStorage.setItem('currentEmailName', emailName);
// Load template data
const emailData = localStorage.getItem('currentEmailData');
const emailName = localStorage.getItem('currentEmailName');
Autosave Functionality
HTML Import Guidelines
HTML Importer API
- Use the HTML Importer API to convert existing HTML templates to Beefree SDK format
- API endpoint:
https://api.getbee.io/v1/conversion/html-to-json
- Reference: HTML Importer API Documentation
Import Process
- Convert HTML templates to Beefree SDK's native JSON format:
const response = await fetch('https://api.getbee.io/v1/conversion/html-to-json', {
method: 'POST',
headers: {
Authorization: 'Bearer Enter Dev Console API Key as Bearer token',
'Content-Type': 'text/html',
},
body: '<!DOCTYPE html><html><body><h1>Hello World</h1></body></html>',
});
const data = await response.json();
Loading Imported Templates
Error Handling Guidelines
onError Callback
Authentication Error Handling
- Handle authentication failures gracefully:
function getBeeToken(callback) {
fetch('/api/beefree/auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
client_id: 'your_client_id',
client_secret: 'your_client_secret',
uid: beeConfig.uid,
}),
})
.then(response => {
if (!response.ok) throw new Error('Auth failed: ' + response.status);
return response.json();
})
.then(data => {
callback(data);
})
.catch(error => {
console.error('Error getting Beefree token:', error);
document.getElementById('beefree-sdk-container').innerHTML =
'<div class="error">Failed to authenticate with Beefree. Please check your credentials and try again.</div>';
});
}
Template Change Tracking Guidelines
Track Message Changes
Change Detection
- Use the
onChange callback to track template changes:onChange: function (jsonFile, response) {
console.log('json', jsonFile);
console.log('response', response);
},
Customization Guidelines
UI Customization
Customize the Beefree SDK appearance with:
Language Customization
- Set the language for internationalization:
const beeConfig = {
container: 'beefree-sdk-container',
language: 'en-US', // or 'es-ES', 'fr-FR', etc.
};
Merge Tags and Special Links
- Configure merge tags and special links for email personalization:
const beeConfig = {
container: 'beefree-sdk-container',
mergeTags: [
{ name: 'First Name', value: '[first_name]' },
{ name: 'Last Name', value: '[last_name]' },
{ name: 'Email', value: '[email]' },
{ name: 'Company', value: '[company]' },
],
specialLinks: [
{ type: 'unsubscribe', label: 'Unsubscribe', link: 'http://[unsubscribe]/' },
{ type: 'subscribe', label: 'Subscribe', link: 'http://[subscribe]/' },
{ type: 'webview', label: 'View in Browser', link: 'http://[webview]/' },
],
};
Other Customizations
Reference the official Beefree SDK technical documentation for a comprehnsive reference of possible customizations.
Best Practices
Performance Optimization
- Initialize the Beefree SDK only when it is actually needed in your application.
- Properly clean up SDK resources when they are no longer required (e.g., when navigating away or closing the editor).
- Handle errors gracefully to prevent application crashes or unexpected behavior.
Security
- Never expose your Beefree SDK client credentials in any frontend or public code.
- Always use a secure backend or proxy server to handle authentication and sensitive operations.
- Validate and sanitize all user inputs before passing them to the SDK to prevent security vulnerabilities.
User Experience
- Show appropriate loading indicators while the SDK is initializing or performing operations.
- Display clear and helpful error messages to users if something goes wrong.
- Implement automatic saving or progress tracking to prevent data loss.
Code Organization
- Keep SDK configuration separate from initialization and business logic for better maintainability.
- Use strong typing (e.g., TypeScript or similar) where possible to improve code safety and clarity.
- Ensure robust error handling throughout your integration, regardless of the tech stack or framework used.
Examples
Complete React Component
Reference the full project at beefree-react-demo.
import { useEffect, useRef } from 'react';
import BeefreeSDK from '@beefree.io/sdk';
export default function BeefreeEditor() {
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
async function initializeEditor() {
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);
}
};
const token = await fetch('http://localhost:3001/proxy/bee-auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ uid: 'demo-user' })
}).then(res => res.json());
const bee = new BeefreeSDK(token);
bee.start(beeConfig, {});
}
initializeEditor();
}, []);
return (
<div
id="beefree-react-demo"
ref={containerRef}
style={{
height: '600px',
width: '90%',
margin: '20px auto',
border: '1px solid #ddd',
borderRadius: '8px'
}}
/>
);
}
Complete HTML Implementation
Reference the complete project at Beefree SDK multiple-versions-concept.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Beefree SDK - Email Builder</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style type="text/css">
#beefree-sdk-container {
position: absolute;
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
}
</style>
</head>
<body>
<div id="beefree-sdk-container"></div>
<script src="https://app-rsrc.getbee.io/plugin/BeefreeSDK.js"></script>
<script type="text/javascript">
const beeConfig = {
container: 'beefree-sdk-container',
uid: 'demo-user-' + Date.now(),
language: 'en-US',
onSave: function (jsonFile, htmlFile) {
console.log('Template saved:', jsonFile);
},
onError: function (errorMessage) {
console.error('Beefree SDK error:', errorMessage);
},
};
function getBeeToken(callback) {
fetch('/api/beefree/auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
client_id: 'your_client_id',
client_secret: 'your_client_secret',
uid: beeConfig.uid,
}),
})
.then(response => response.json())
.then(data => callback(data))
.catch(error => {
console.error('Error getting Beefree token:', error);
});
}
function initializeBeefree(authResponse) {
BeefreeSDK.create(authResponse, beeConfig, function (beefreeSDKInstance) {
console.log('Beefree SDK initialized successfully');
beefreeSDKInstance.start();
});
}
getBeeToken(initializeBeefree);
</script>
</body>
</html>
Memory Protocol (MANDATORY)
Before starting:
cat .claude/context/memory/learnings.md
After completing: Record any new patterns or exceptions discovered.
ASSUME INTERRUPTION: Your context may reset. If it's not in memory, it didn't happen.
1---
2name: beefreesdk
3description: Guidelines and best practices for building applications with [Beefree SDK](https://docs.beefree.io/beefree-sdk), including installation, authentication, configuration, customization, and template mana
4version: 1.0.0
5model: sonnet
6invoked_by: both
7user_invocable: true
8tools: [Read, Write, Edit, Bash]
9globs: '**/*.{ts,tsx,js,jsx,html,css}'
10best_practices:
11 - Follow the guidelines consistently
12 - Apply rules during code review
13 - Use as reference when writing new code
14error_handling: graceful
15streaming: supported
16metadata:
17 source: https://skillmd.com/skills/aibot88/beefreesdk
18---
19
20# Beefreesdk Skill
21
22<identity>
23You are a coding standards expert specializing in beefreesdk.
24You help developers write better code by applying established guidelines and best practices.
25</identity>
26
27<capabilities>
28- Review code for guideline compliance
29- Suggest improvements based on best practices
30- Explain why certain patterns are preferred
31- Help refactor code to meet standards
32</capabilities>
33
34<instructions>
35When reviewing or writing code, apply these guidelines:
36
37# Beefree SDK Guidelines
38
39Guidelines and best practices for building applications with [Beefree SDK](https://docs.beefree.io/beefree-sdk), including installation, authentication, configuration, customization, and template management.
40
41## Installation Guidelines
42
43### Package Installation
44
45- Install the Beefree SDK package using npm or yarn:
46 ```bash
47 npm install @beefree.io/sdk
48 # or
49 yarn add @beefree.io/sdk
50 ```
51
52### Dependencies
53
54- Beefree SDK requires the following core dependencies:
55 ```json
56 {
57 "dependencies": {
58 "@beefree.io/sdk": "^9.0.2-fix-optional-url-config.0",
59 "axios": "^1.10.0",
60 "express": "^5.1.0",
61 "cors": "^2.8.5",
62 "dotenv": "^17.2.0"
63 }
64 }
65 ```
66
67### Environment Setup
68
69- Create a `.env` file in your project root with your Beefree credentials:
70 ```env
71 BEE_CLIENT_ID=your_client_id_here
72 BEE_CLIENT_SECRET=your_client_secret_here
73 ```
74
75## Authentication Guidelines
76
77### Proxy Server Setup
78
79- ALWAYS use a proxy server for authentication to protect your credentials
80- Create a proxy server file (e.g., `proxy-server.js`) to handle authentication:
81
82 ```javascript
83 import express from 'express';
84 import cors from 'cors';
85 import axios from 'axios';
86 import dotenv from 'dotenv';
87
88 dotenv.config();
89
90 const app = express();
91 const PORT = 3001;
92
93 app.use(cors());
94 app.use(express.json());
95
96 const BEE_CLIENT_ID = process.env.BEE_CLIENT_ID;
97 const BEE_CLIENT_SECRET = process.env.BEE_CLIENT_SECRET;
98
99 // V2 Auth Endpoint
100 app.post('/proxy/bee-auth', async (req, res) => {
101 try {
102 const { uid } = req.body;
103
104 const response = await axios.post(
105 'https://auth.getbee.io/loginV2',
106 {
107 client_id: BEE_CLIENT_ID,
108 client_secret: BEE_CLIENT_SECRET,
109 uid: uid || 'demo-user',
110 },
111 { headers: { 'Content-Type': 'application/json' } }
112 );
113
114 res.json(response.data);
115 } catch (error) {
116 console.error('Auth error:', error.message);
117 res.status(500).json({ error: 'Failed to authenticate' });
118 }
119 });
120
121 app.listen(PORT, () => {
122 console.log(`Proxy server running on http://localhost:${PORT}`);
123 });
124 ```
125
126### Authentication Process
127
128- Use the V2 authentication endpoint: `https://auth.getbee.io/loginV2`
129- Pass the ENTIRE API response to the Beefree SDK, not just the token
130- Example authentication call:
131 ```typescript
132 const token = await fetch('http://localhost:3001/proxy/bee-auth', {
133 method: 'POST',
134 headers: { 'Content-Type': 'application/json' },
135 body: JSON.stringify({ uid: 'demo-user' }),
136 }).then(res => res.json());
137 ```
138
139## Container Setup Guidelines
140
141### HTML Container
142
143- Create a dedicated container element for the Beefree SDK:
144 ```html
145 <div id="beefree-sdk-container"></div>
146 ```
147
148### CSS Styling
149
150- Style the container to ensure proper display:
151 ```css
152 #beefree-sdk-container {
153 position: absolute;
154 top: 0px;
155 bottom: 0px;
156 left: 0px;
157 right: 0px;
158 height: 600px;
159 width: 90%;
160 margin: 20px auto;
161 border: 1px solid #ddd;
162 border-radius: 8px;
163 }
164 ```
165
166### React Container
167
168- For React applications, the following code snippet shows an example using refs to manage the container:
169
170 ```typescript
171 const containerRef = useRef<HTMLDivElement>(null);
172
173 return (
174 <div
175 id="beefree-react-demo"
176 ref={containerRef}
177 style={{
178 height: '600px',
179 width: '90%',
180 margin: '20px auto',
181 border: '1px solid #ddd',
182 borderRadius: '8px'
183 }}
184 />
185 );
186 ```
187
188## Configuration Guidelines
189
190### Required Configuration Parameters
191
192- ALWAYS include the `container` parameter in your configuration:
193 ```typescript
194 const beeConfig = {
195 container: 'beefree-sdk-container', // Required
196 language: 'en-US',
197 };
198 ```
199
200### Optional Configuration Parameters
201
202- Customize your SDK with optional parameters:
203 ```typescript
204 const beeConfig = {
205 container: 'beefree-sdk-container', // Required
206 language: 'en-US',
207 specialLinks: [
208 {
209 type: 'unsubscribe',
210 label: 'Unsubscribe',
211 link: 'http://[unsubscribe]/',
212 },
213 {
214 type: 'subscribe',
215 label: 'Subscribe',
216 link: 'http://[subscribe]/',
217 },
218 ],
219 mergeTags: [
220 {
221 name: 'First Name',
222 value: '[first_name]',
223 },
224 {
225 name: 'Last Name',
226 value: '[last_name]',
227 },
228 {
229 name: 'Email',
230 value: '[email]',
231 },
232 ],
233 };
234 ```
235
236### Callback Functions
237
238- Implement essential callback functions for proper functionality:
239 ```typescript
240 const beeConfig = {
241 container: 'beefree-sdk-container',
242 onSave: function (jsonFile, htmlFile) {
243 console.log('Template saved:', jsonFile);
244 // Implement custom save logic here
245 },
246 onAutoSave: function (jsonFile) {
247 console.log('Auto-saving template...');
248 localStorage.setItem('email.autosave', jsonFile);
249 },
250 onSend: function (htmlFile) {
251 console.log('Email ready to send:', htmlFile);
252 // Implement custom send logic here
253 },
254 onError: function (errorMessage) {
255 console.error('Beefree SDK error:', errorMessage);
256 // Handle errors appropriately
257 },
258 };
259 ```
260
261## SDK Initialization Guidelines
262
263### Basic Initialization
264
265- Initialize the Beefree SDK with proper error handling:
266 ```typescript
267 async function initializeBeefree(authResponse) {
268 try {
269 const bee = new BeefreeSDK(authResponse);
270 bee.start(beeConfig, {});
271 console.log('Beefree SDK initialized successfully');
272 } catch (error) {
273 console.error('Failed to initialize Beefree SDK:', error);
274 }
275 }
276 ```
277
278### React Integration
279
280- For React applications, the following code snippet shows an example using useEffect for initialization:
281
282 ```typescript
283 useEffect(() => {
284 async function initializeEditor() {
285 const beeConfig = {
286 container: 'beefree-react-demo',
287 language: 'en-US',
288 onSave: (
289 pageJson: string,
290 pageHtml: string,
291 ampHtml: string | null,
292 templateVersion: number,
293 language: string | null
294 ) => {
295 console.log('Saved!', { pageJson, pageHtml, ampHtml, templateVersion, language });
296 },
297 onError: (error: unknown) => {
298 console.error('Error:', error);
299 },
300 };
301
302 const token = await fetch('http://localhost:3001/proxy/bee-auth', {
303 method: 'POST',
304 headers: { 'Content-Type': 'application/json' },
305 body: JSON.stringify({ uid: 'demo-user' }),
306 }).then(res => res.json());
307
308 const bee = new BeefreeSDK(token);
309 bee.start(beeConfig, {});
310 }
311
312 initializeEditor();
313 }, []);
314 ```
315
316## Template Loading Guidelines
317
318### Loading Templates
319
320- Use the `start()` method with template data to load existing templates:
321
322 ```typescript
323 // Load template from localStorage
324 const selectedTemplate = JSON.parse(localStorage.getItem('currentEmailData'));
325
326 if (selectedTemplate) {
327 beefreeSDKInstance.start(selectedTemplate);
328 console.log('Loaded template from localStorage');
329 } else {
330 // Start with empty template
331 beefreeSDKInstance.start();
332 console.log('Started with empty template');
333 }
334 ```
335
336### Template Storage
337
338- Store templates in localStorage for persistence while testing:
339
340 ```typescript
341 // Save template data
342 localStorage.setItem('currentEmailData', JSON.stringify(templateData));
343 localStorage.setItem('currentEmailName', emailName);
344
345 // Load template data
346 const emailData = localStorage.getItem('currentEmailData');
347 const emailName = localStorage.getItem('currentEmailName');
348 ```
349
350### Autosave Functionality
351
352- Implement autosave to prevent data loss:
353 ```typescript
354 onAutoSave: function (jsonFile) {
355 console.log("Auto-saving template...");
356 localStorage.setItem("email.autosave", jsonFile);
357 }
358 ```
359
360## HTML Import Guidelines
361
362### HTML Importer API
363
364- Use the HTML Importer API to convert existing HTML templates to Beefree SDK format
365- API endpoint: `https://api.getbee.io/v1/conversion/html-to-json`
366- Reference: [HTML Importer API Documentation](https://docs.beefree.io/beefree-sdk/apis/html-importer-api/import-html)
367
368### Import Process
369
370- Convert HTML templates to Beefree SDK's native JSON format:
371 ```javascript
372 const response = await fetch('https://api.getbee.io/v1/conversion/html-to-json', {
373 method: 'POST',
374 headers: {
375 Authorization: 'Bearer Enter Dev Console API Key as Bearer token',
376 'Content-Type': 'text/html',
377 },
378 body: '<!DOCTYPE html><html><body><h1>Hello World</h1></body></html>',
379 });
380 const data = await response.json();
381 ```
382
383### Loading Imported Templates
384
385- Load imported templates into the Beefree SDK:
386 ```typescript
387 const importedTemplate = await importHtmlTemplate(htmlContent);
388 beefreeSDK.start(importedTemplate);
389 ```
390
391## Error Handling Guidelines
392
393### onError Callback
394
395- ALWAYS implement the `onError` callback to handle SDK errors:
396 ```typescript
397 onError: function (errorMessage) {
398 console.error("Beefree SDK error:", errorMessage);
399 // Display user-friendly error message
400 document.getElementById('beefree-sdk-container').innerHTML =
401 '<div class="error">Error loading Beefree SDK: ' + errorMessage.message + '</div>';
402 }
403 ```
404
405### Authentication Error Handling
406
407- Handle authentication failures gracefully:
408 ```typescript
409 function getBeeToken(callback) {
410 fetch('/api/beefree/auth', {
411 method: 'POST',
412 headers: { 'Content-Type': 'application/json' },
413 body: JSON.stringify({
414 client_id: 'your_client_id',
415 client_secret: 'your_client_secret',
416 uid: beeConfig.uid,
417 }),
418 })
419 .then(response => {
420 if (!response.ok) throw new Error('Auth failed: ' + response.status);
421 return response.json();
422 })
423 .then(data => {
424 callback(data);
425 })
426 .catch(error => {
427 console.error('Error getting Beefree token:', error);
428 document.getElementById('beefree-sdk-container').innerHTML =
429 '<div class="error">Failed to authenticate with Beefree. Please check your credentials and try again.</div>';
430 });
431 }
432 ```
433
434## Template Change Tracking Guidelines
435
436### Track Message Changes
437
438- Implement template change tracking to monitor changes made by end users
439- Reference: [Track Message Changes Documentation](https://docs.beefree.io/beefree-sdk/getting-started/tracking-message-changes)
440
441### Change Detection
442
443- Use the `onChange` callback to track template changes:
444 ```typescript
445 onChange: function (jsonFile, response) {
446 console.log('json', jsonFile);
447 console.log('response', response);
448 },
449 ```
450
451## Customization Guidelines
452
453### UI Customization
454
455Customize the Beefree SDK appearance with:
456
457- [Customized Themes](https://docs.beefree.io/beefree-sdk/other-customizations/appearance/themes)
458- [Custom CSS](https://docs.beefree.io/beefree-sdk/other-customizations/appearance/custom-css)
459
460### Language Customization
461
462- Set the language for internationalization:
463 ```typescript
464 const beeConfig = {
465 container: 'beefree-sdk-container',
466 language: 'en-US', // or 'es-ES', 'fr-FR', etc.
467 };
468 ```
469
470### Merge Tags and Special Links
471
472- Configure merge tags and special links for email personalization:
473 ```typescript
474 const beeConfig = {
475 container: 'beefree-sdk-container',
476 mergeTags: [
477 { name: 'First Name', value: '[first_name]' },
478 { name: 'Last Name', value: '[last_name]' },
479 { name: 'Email', value: '[email]' },
480 { name: 'Company', value: '[company]' },
481 ],
482 specialLinks: [
483 { type: 'unsubscribe', label: 'Unsubscribe', link: 'http://[unsubscribe]/' },
484 { type: 'subscribe', label: 'Subscribe', link: 'http://[subscribe]/' },
485 { type: 'webview', label: 'View in Browser', link: 'http://[webview]/' },
486 ],
487 };
488 ```
489
490### Other Customizations
491
492Reference the official [Beefree SDK technical documentation](https://docs.beefree.io/beefree-sdk) for a comprehnsive reference of possible customizations.
493
494## Best Practices
495
496### Performance Optimization
497
498- Initialize the Beefree SDK only when it is actually needed in your application.
499- Properly clean up SDK resources when they are no longer required (e.g., when navigating away or closing the editor).
500- Handle errors gracefully to prevent application crashes or unexpected behavior.
501
502### Security
503
504- **Never** expose your Beefree SDK client credentials in any frontend or public code.
505- Always use a secure backend or proxy server to handle authentication and sensitive operations.
506- Validate and sanitize all user inputs before passing them to the SDK to prevent security vulnerabilities.
507
508### User Experience
509
510- Show appropriate loading indicators while the SDK is initializing or performing operations.
511- Display clear and helpful error messages to users if something goes wrong.
512- Implement automatic saving or progress tracking to prevent data loss.
513
514### Code Organization
515
516- Keep SDK configuration separate from initialization and business logic for better maintainability.
517- Use strong typing (e.g., TypeScript or similar) where possible to improve code safety and clarity.
518- Ensure robust error handling throughout your integration, regardless of the tech stack or framework used.
519
520## Examples
521
522### Complete React Component
523
524Reference the full project at [beefree-react-demo](https://github.com/BeefreeSDK/beefree-react-demo).
525
526```typescript
527import { useEffect, useRef } from 'react';
528import BeefreeSDK from '@beefree.io/sdk';
529
530export default function BeefreeEditor() {
531 const containerRef = useRef<HTMLDivElement>(null);
532
533 useEffect(() => {
534 async function initializeEditor() {
535 const beeConfig = {
536 container: 'beefree-react-demo',
537 language: 'en-US',
538 onSave: (pageJson: string, pageHtml: string, ampHtml: string | null, templateVersion: number, language: string | null) => {
539 console.log('Saved!', { pageJson, pageHtml, ampHtml, templateVersion, language });
540 },
541 onError: (error: unknown) => {
542 console.error('Error:', error);
543 }
544 };
545
546 const token = await fetch('http://localhost:3001/proxy/bee-auth', {
547 method: 'POST',
548 headers: { 'Content-Type': 'application/json' },
549 body: JSON.stringify({ uid: 'demo-user' })
550 }).then(res => res.json());
551
552 const bee = new BeefreeSDK(token);
553 bee.start(beeConfig, {});
554 }
555
556 initializeEditor();
557 }, []);
558
559 return (
560 <div
561 id="beefree-react-demo"
562 ref={containerRef}
563 style={{
564 height: '600px',
565 width: '90%',
566 margin: '20px auto',
567 border: '1px solid #ddd',
568 borderRadius: '8px'
569 }}
570 />
571 );
572}
573```
574
575### Complete HTML Implementation
576
577Reference the complete project at Beefree SDK [multiple-versions-concept](https://github.com/BeefreeSDK/beefree-sdk-simple-schema/tree/main/multiple-versions-concept).
578
579```html
580<!DOCTYPE html>
581<html lang="en">
582 <head>
583 <title>Beefree SDK - Email Builder</title>
584 <meta charset="utf-8" />
585 <meta name="viewport" content="width=device-width, initial-scale=1" />
586 <style type="text/css">
587 #beefree-sdk-container {
588 position: absolute;
589 top: 0px;
590 bottom: 0px;
591 left: 0px;
592 right: 0px;
593 }
594 </style>
595 </head>
596 <body>
597 <div id="beefree-sdk-container"></div>
598 <script src="https://app-rsrc.getbee.io/plugin/BeefreeSDK.js"></script>
599 <script type="text/javascript">
600 const beeConfig = {
601 container: 'beefree-sdk-container',
602 uid: 'demo-user-' + Date.now(),
603 language: 'en-US',
604 onSave: function (jsonFile, htmlFile) {
605 console.log('Template saved:', jsonFile);
606 },
607 onError: function (errorMessage) {
608 console.error('Beefree SDK error:', errorMessage);
609 },
610 };
611
612 function getBeeToken(callback) {
613 fetch('/api/beefree/auth', {
614 method: 'POST',
615 headers: { 'Content-Type': 'application/json' },
616 body: JSON.stringify({
617 client_id: 'your_client_id',
618 client_secret: 'your_client_secret',
619 uid: beeConfig.uid,
620 }),
621 })
622 .then(response => response.json())
623 .then(data => callback(data))
624 .catch(error => {
625 console.error('Error getting Beefree token:', error);
626 });
627 }
628
629 function initializeBeefree(authResponse) {
630 BeefreeSDK.create(authResponse, beeConfig, function (beefreeSDKInstance) {
631 console.log('Beefree SDK initialized successfully');
632 beefreeSDKInstance.start();
633 });
634 }
635
636 getBeeToken(initializeBeefree);
637 </script>
638 </body>
639</html>
640```
641
642</instructions>
643
644<examples>
645Example usage:
646```
647User: "Review this code for beefreesdk compliance"
648Agent: [Analyzes code against guidelines and provides specific feedback]
649```
650</examples>
651
652## Memory Protocol (MANDATORY)
653
654**Before starting:**
655
656```bash
657cat .claude/context/memory/learnings.md
658```
659
660**After completing:** Record any new patterns or exceptions discovered.
661
662> ASSUME INTERRUPTION: Your context may reset. If it's not in memory, it didn't happen.