Login Sign Up

JS Embed SDK & API Reference Guide

Integrate Embedenv compiler sandboxes directly onto any external technology blog, tutorial website, or LMS system. We offer two distinct SDK architectures designed for different product experiences, and choose a version that fits your project needs below:

Make sure you have sufficient Runs Credits on your dashboard before deploying embedded code terminals on high-traffic production websites.

Choose Your SDK Version

Compare the capabilities, scripts, and target workflows of our Standard and Pro SDK versions:

Standard SDK
Sandbox Studio (One-Click)

Automatically converts standard blog code blocks (<pre><code>) in interactive CodeMirror sandboxes. Best for dev blogs, documentation hubs. Rapid setup.

  • Automatic language detection & code editor wraps
  • Smart filters: leaves configuration and plain text untouched
  • Easy styling options configured via script data attributes
Script Tag URL:
<script src="https://embedenv.com/static/main/studio/js/embed.js" data-key="YOUR_KEY" defer></script>
View Standard SDK Setup
Pro SDK
Custom Canvas Embed

Loads specific interactive layouts designed visually inside the Layout Studio, and best for complex, customized single-terminal layouts and styled design canvases.

  • Renders structures designed in our visual builder canvas
  • Explicitly targets container elements with class .embedenv-code-embed
  • Supports Domain Lock (Test Mode) and HMAC (Secure Mode)
Script Tag URL:
<script src="https://embedenv.com/embed.js" data-key="YOUR_KEY" defer></script>
View Pro SDK Setup

2. Standard Sandbox SDK (One-Click)

The Standard Sandbox SDK scans your HTML page for existing code blocks and automatically wraps them in interactive CodeMirror compilation frames. It automatically handles brack matching, syntax highlighting, real-time debounced auto-saving (300ms) over WebSockets, and terminal execution logs.

standard_sdk_integration.html
<script src="https://embedenv.com/static/main/studio/js/embed.js" data-key="YOUR_PUBLIC_KEY" defer></script>

Security Models Support (Test Mode vs Secure Mode)

The Standard Sandbox SDK supports both security models out-of-the-box, allowing you to lock execution to authorized domains:

1. Test Mode (Quick Lock Domain Verification)

Specify only your public key. Origin headers are verified automatically against registered domains:

<script src="https://embedenv.com/static/main/studio/js/embed.js" data-key="YOUR_PUBLIC_KEY" defer></script>

2. Secure Mode (HMAC Signature Handshake)

Add the data-backend attribute pointing to your server route that signs token handshakes backend-to-backend:

<script src="https://embedenv.com/static/main/studio/js/embed.js" data-key="YOUR_PUBLIC_KEY" data-backend="/embed-verify" defer></script>

Smart Text & Console Output Filtering

To avoid rendering non-runnable files or console logs as editors, the Standard SDK uses an explicit whitelist: ['python', 'javascript', 'c', 'cpp', 'c++', 'java', 'go', 'golang', 'rust', 'php', 'ruby', 'html'].

Any code block matching plain text (e.g. plaintext, language-text), configuration formats (JSON, YAML, TOML), markdown, or command line console outputs (bash commands, terminal logs, output dumps) is automatically bypassed and left to render as standard static code.

Global Configuration Attributes

Configure page-wide compiler layout and behavior defaults by specifying attributes on a script tag itself:

Attribute Description Allowed Options / Examples
data-theme Selects a code editor theme material-darker, dracula, monokai, github-dark, nord
data-accent Hex value defining the theme primary highlight color #6366f1, #f472b6, #10b981
data-radius Border radius rounding for editor panels (in pixels) 8, 12, 16 (default: 10)
data-fontsize Font size for the editor container (in pixels) 12, 14, 16 (default: 14)
data-height Default height of the sandbox widget frame 350px, 450px, 500px
data-readonly Disables browser editing, turning blocks into execution-only widgets true or false (default: false)

Per-Block Configurations

You can override global configuration settings for specific individual code blocks by passing settings as attributes directly on the wrapping <pre> element:

Override Attribute Description Allowed Options / Examples
data-lang / lang-name Explicitly declares a programming language python, javascript, c, java, rust
data-theme Overrides default page theme for this block dracula, monokai
data-height Overrides layout default height for this block 300px, 500px
data-readonly Forces read-only behavior for this block only true or false
Example: Customized python code block setup
<pre lang-name="python" data-theme="dracula" data-height="350px" data-readonly="false"><code>def calculate(x, y):
 return x * y

print("Calculated:", calculate(10, 5))</code></pre>

3, and pro Custom Canvas SDK (Visual Builder)

The Pro SDK loads specific compiler layouts built visually using our **Layout Studio**. Instead of replacing standard code blocks globally, it renders structured IDE canvas blocks directly inside marked container tags.

To integrate, place the target container element anywhere in your HTML document, and the Pro SDK script scans your page for this container class and builds the custom layout on load:

target_container.html
<div class="embedenv-code-embed" data-embed-id="YOUR_LAYOUT_ID"></div>
pro_sdk_script.html
<script src="https://embedenv.com/embed.js" data-key="YOUR_PUBLIC_KEY" defer></script>

Choose Your Security Model

The Pro Custom Canvas SDK supports two different levels of host domain restrictions:

  • Test Mode Setup (Domain Restrict Mode): Best for quick lock verification. Checks header origins directly on our CDN side.
  • Secure Mode Setup (HMAC Verification Mode): Best for premium enterprise workspaces. Dispatches signature validation tokens backend-to-backend to prevent developer keys from being exploited on unauthorized pages.

4. Pro SDK - Test Mode Setup

Test mode allows immediate frontend execution by authenticating with your public access key. The system validates a HTTP origin header against the host domain names registered inside your Embedenv developer dashboard.

Method A: Script Query Parameter

Load a script tag while passing your public key directly in the URL query string parameters:

method_a_script_tag.html
<script src="https://embedenv.com/embed.js?key=YOUR_PUBLIC_KEY" defer></script>

Method B: Hidden Key Integrations

Hide the public key value from basic crawler scrapers using these script data attribute configurations:

Option B1: data-key script attribute

option_b1.html
<script src="https://embedenv.com/embed.js" data-key="YOUR_PUBLIC_KEY" defer></script>

Option B2: Global Config Variable

option_b2.html
<script>
 window.EMBED_PUBLIC_KEY = "YOUR_PUBLIC_KEY";
</script>
<script src="https://embedenv.com/embed.js" defer></script>
Live Production Validation Proxy Pipeline
https://your-site.com/tutorial
<pre>const sample = "static code";</pre>
<pre>const sample = "persamples";</pre>
<pre>const sample = "interactivity";</pre>
Proxy Injection
https://your-site.com/tutorial (Sandboxed)
1 const liveCode = "interactive!";
2
3 console.log(liveCode);
3-Step Sandbox Web Tester Flow
1. Retrieve

Our server-side proxy fetches the target website's live HTML source code securely in the low-latency WebSocket pipeline.

2. Inject

The system dynamically injects the asynchronous embed.js SDK script tag into a HTML stream.

3. Transform

The browser renders the target page locally, instantly converting static <pre> blocks into live compilers.

5. Pro SDK - Secure Mode Setup (HMAC Verification)

Secure mode uses signature token handshakes to block credentials hijacking. The public key is loaded in the browser, but the secret validation key is kept safe on your backend web server, and when the browser requests layout loading, your server validates a header origins and signs the request using HMAC-SHA256, returning the transient (5-minute expiration) verified key.

embed_secure_script.html
<script src="https://embedenv.com/embed.js?key=YOUR_PUBLIC_KEY" data-backend="https://your-site.com/embed-verify" defer></script>

Signature verification workflow

1. When layout starts loading, the SDK POSTs the target details to your server's validation route (data-backend):

POST /embed-verify (Received by your backend server)
{
 "public_key": "YOUR_PUBLIC_KEY",
 "origin": "https://your-blog.com"
}

2. Your backend signs a request and forwards it to the Embedenv authentication API using your private secret key:

POST https://embedenv.com/api/embed/secure-verify/ (Payload your server forwards to Embedenv)
{
 "public_key": "YOUR_PUBLIC_KEY",
 "secret_key": "YOUR_PRIVATE_SECRET_KEY",
 "origin": "https://your-blog.com"
}
HMAC Signature Verification Architecture

1. Client Browser

Dispatches sandbox workspace request to client backend.
Dispatches request
Private key never touches browser

2, and client Backend

Signs verification token via secure HMAC-SHA256 signature protocol.

3, and embedenv Engine

Returns 5-minute verified join_key to authenticate execution session.
Signs & validates
HMAC Token Handshake
Strict Shell Safety: Client-side execution blacklist instantly aborts system-destructive commands (e.g., rm -rf, sudo).

6. Secure Mode Backend Integrations (Standard & Pro SDK)

Below are single-file implementation blueprints showing verification handlers and HTML frontends for a most popular web development stacks:

app.py (Flask Backend)
import requests
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

# Replace with credentials from your Embedenv Dashboard
PUBLIC_KEY = "YOUR_PUBLIC_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"
DJANGO_API_URL = "https://embedenv.com/api/embed/secure-verify/"

@app.route("/")
def index():
 return render_template("index.html", public_key=PUBLIC_KEY)

@app.route("/embed-verify", methods=["POST"])
def embed_verify():
 try:
 data = request.get_json() or {}
 public_key = data.get("public_key")
 origin = data.get("origin")
 
 if not public_key or not origin:
 return jsonify({"verified": False, "error": "Missing public_key or origin"}), 400
 
 # Verify credentials backend-to-backend with Secure Verify API
 payload = {
 "public_key": PUBLIC_KEY,
 "secret_key": SECRET_KEY,
 "origin": origin
 }
 
 response = requests.post(DJANGO_API_URL, json=payload, timeout=10)
 if response.status_code == 200:
 django_data = response.json()
 if django_data.get("verified"):
 return jsonify({
 "verified": True,
 "join_key": django_data.get("token")
 })
 
 err_msg = response.json().get("error", "Secure verification failed")
 return jsonify({"verified": False, "error": err_msg}), 403
 
 except Exception as e:
 return jsonify({"verified": False, "error": str(e)}), 500

if __name__ == "__main__":
 app.run(host="0.0.0.0", port=5000)
templates/index.html (HTML Frontend)
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Flask Sandbox Integration</title>
 
 <!-- Domain Ownership Verification Meta Tag -->
 <meta name="embedenv-verification" content="YOUR_VERIFICATION_TOKEN">
</head>
<body>
 <h1>Interactive Sandbox Integration</h1>
 
 <!-- Target Canvas Frame Container -->
 <div class="embedenv-code-embed" data-embed-id="YOUR_LAYOUT_ID"></div>

 <!-- EmbedJS Dynamic SDK Loader (Secure Mode) -->
 <script 
 src="https://embedenv.com/embed.js?key=YOUR_PUBLIC_KEY" 
 data-backend="/embed-verify" 
 defer>
 </script>
</body>
</html>
server.js (Express/Node.js Backend)
const express = require('express');
const axios = require('axios');
const path = require('path');

const app = express();
app.use(express.json());

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs'); 

// Replace with credentials from your Embedenv Dashboard
const PUBLIC_KEY = "YOUR_PUBLIC_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";
const DJANGO_API_URL = "https://embedenv.com/api/embed/secure-verify/";

app.get("/", (req, res) => {
 res.render("index", { publicKey: PUBLIC_KEY });
});

app.post("/embed-verify", async (req, res) => {
 try {
 const { public_key, origin } = req.body;
 
 if (!public_key ||!origin) {
 return res.status(400).json({ verified: false, error: "Missing public_key or origin" });
 }
 
 const payload = {
 public_key: PUBLIC_KEY,
 secret_key: SECRET_KEY,
 origin: origin
 };
 
 const response = await axios.post(DJANGO_API_URL, payload, { timeout: 10000 });
 if (response.status === 200 && response.data.verified) {
 return res.json({
 verified: true,
 join_key: response.data.token
 });
 }
 return res.status(403).json({ verified: false, error: "Secure verification failed" });
 } catch (error) {
 const errMsg = error.response && error.response.data? error.response.data.error: error.message;
 return res.status(500).json({ verified: false, error: errMsg });
 }
});

app.listen(3000, () => {
 console.log('Server listening on port 3000');
});
views/index.ejs (Express/EJS Frontend)
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Express Embedenv Sandbox</title>
 
 <!-- Domain Ownership Verification Meta Tag -->
 <meta name="embedenv-verification" content="YOUR_VERIFICATION_TOKEN">
</head>
<body>
 <h1>Interactive Node.js Sandbox</h1>
 
 <!-- Canvas Container -->
 <div class="embedenv-code-embed" data-embed-id="YOUR_LAYOUT_ID"></div>

 <!-- Secure Mode Loader -->
 <script 
 src="https://embedenv.com/embed.js?key=<%= publicKey %>" 
 data-backend="/embed-verify" 
 defer>
 </script>
</body>
</html>
main.py (FastAPI Single Script)
import httpx
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from pydantic import BaseModel

app = FastAPI()

# Replace with credentials from your Embedenv Dashboard
PUBLIC_KEY = "YOUR_PUBLIC_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"
DJANGO_API_URL = "https://embedenv.com/api/embed/secure-verify/"

class VerifyPayload(BaseModel):
 public_key: str
 origin: str

@app.get("/", response_class=HTMLResponse)
async def read_index():
 return f"""
 <!DOCTYPE html>
 <html>
 <head>
 <title>FastAPI Embedenv Sandbox</title>
 <!-- Domain Verification Meta Tag -->
 <meta name="embedenv-verification" content="YOUR_VERIFICATION_TOKEN">
 </head>
 <body>
 <h1>FastAPI Unified Code Sandbox</h1>
 
 <!-- Custom Canvas Frame Container -->
 <div class="embedenv-code-embed" data-embed-id="YOUR_LAYOUT_ID"></div>

 <!-- Secure Mode Script Loader -->
 <script src="https://embedenv.com/embed.js?key={PUBLIC_KEY}" data-backend="/embed-verify" defer></script>
 </body>
 </html>
 """

@app.post("/embed-verify")
async def embed_verify(payload: VerifyPayload):
 async with httpx.AsyncClient() as client:
 django_payload = {
 "public_key": PUBLIC_KEY,
 "secret_key": SECRET_KEY,
 "origin": payload.origin
 }
 try:
 response = await client.post(DJANGO_API_URL, json=django_payload, timeout=10.0)
 if response.status_code == 200:
 data = response.json()
 if data.get("verified"):
 return {"verified": True, "join_key": data.get("token")}
 raise HTTPException(status_code=403, detail="Signature verification failed")
 except httpx.RequestError as e:
 raise HTTPException(status_code=500, detail=f"Request to verification API failed: {str(e)}")

if __name__ == "__main__":
 import uvicorn
 uvicorn.run(app, host="0.0.0.0", port=8000)
index.php (Combined Single File PHP script)
<?php
$public_key = "YOUR_PUBLIC_KEY";
$secret_key = "YOUR_SECRET_KEY";
$django_api_url = "https://embedenv.com/api/embed/secure-verify/";

// Handle signature POST route
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_SERVER['REQUEST_URI'] === '/embed-verify') {
 header('Content-Type: application/json');
 $input = json_decode(file_get_contents('php://input'), true);
 
 $pub = $input['public_key']?? '';
 $org = $input['origin']?? '';
 
 if (empty($pub) || empty($org)) {
 http_response_code(400);
 echo json_encode(["verified" => false, "error" => "Missing public_key or origin"]);
 exit;
 }
 
 // Prepare cURL payload
 $payload = json_encode([
 "public_key" => $public_key,
 "secret_key" => $secret_key,
 "origin" => $org
 ]);
 
 $ch = curl_init($django_api_url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_POST, true);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
 curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
 
 $response = curl_exec($ch);
 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
 curl_close($ch);
 
 if ($http_code === 200) {
 $data = json_decode($response, true);
 if ($data['verified']) {
 echo json_encode([
 "verified" => true,
 "join_key" => $data['token']
 ]);
 exit;
 }
 }
 
 http_response_code(403);
 echo json_encode(["verified" => false, "error" => "Secure verification failed"]);
 exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>PHP Embedenv Sandbox Integration</title>
 
 <!-- Domain Verification Meta Tag -->
 <meta name="embedenv-verification" content="YOUR_VERIFICATION_TOKEN">
</head>
<body>
 <h1>PHP Integrated Script Sandbox</h1>
 
 <!-- Target Canvas Frame Container -->
 <div class="embedenv-code-embed" data-embed-id="YOUR_LAYOUT_ID"></div>

 <!-- Secure Mode Loader -->
 <script 
 src="https://embedenv.com/embed.js?key=<?php echo $public_key;?>" 
 data-backend="/embed-verify" 
 defer>
 </script>
</body>
</html>

7. REST API Endpoints (Standard & Pro SDK)

Build custom admin dashboards and verify credentials server-side with our REST API endpoints:

POST /api/embed/generate-key/
// Content-Type: application/json
{
 "domain": "your-blog.com",
 "mode": "test"
}
GET /api/embed/validate-key/
// Query Params: key=YOUR_PUBLIC_KEY&origin=https://your-blog.com
// Validates domain match and returns Layout Studio customization profiles
POST /api/embed/secure-verify/
// Content-Type: application/json
// Performs HMAC handshake and returns a 5-minute verified session token
{
 "public_key": "YOUR_PUBLIC_KEY",
 "secret_key": "YOUR_PRIVATE_SECRET_KEY",
 "origin": "https://your-blog.com"
}