Login Sign Up

JS Embed SDK & API Docs

Integrate Embedenv compiler sandboxes directly onto any external technology blog, tutorial site, or LMS platform. We support two security models: Test Mode (quick lock domain integration) and Secure Mode (signature-based HMAC backend checks).

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

1. Test Mode Setup

Test mode allows immediate embedding using only your public_key (access token). Embedenv validates domain headers automatically against the registered hostname and allows up to 1,000 runs before requiring an upgrade.

We provide two beautiful integration styles to connect the JS Embed SDK (styled dynamically via Layout Studio):

Method A: Standard URL Parameter (Public Key Visible)

Specify the public API key directly in the src URL query string of the script tag. This is the simplest integration method.

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

Method B: Hidden Key Integration (Key Hidden from URL)

If you prefer not to expose the public key in your script tag's src parameter, we offer two secure alternatives:

Option B1: Using script data-key attribute

Keep the script URL clean and supply your key as a custom data-key attribute on the script tag itself:

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

Option B2: Using global Javascript config variable

Declare your public key inside a global window.EMBED_PUBLIC_KEY variable before importing the clean script tag:

method_b2_global_var.html
<script>
  window.EMBED_PUBLIC_KEY = "YOUR_PUBLIC_KEY";
</script>
<script src="https://embedenv.com/embed.js" defer></script>
Live Production Validation Without Code Changes
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 a low-latency WebSocket pipeline.

2. Inject

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

3. Transform

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

2. Secure Mode Setup

Secure mode requires both a public and a private key. The public key resides in the browser, and the private key lives only on your server backend. The frontend embed communicates with your backend, which in turn signs transactions with Embedenv secure verification.

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

Your backend server endpoint (e.g. /embed-verify) receives browser headers and forwards them with your secret key to our verify pipeline.

POST /embed-verify (Payload structure received by your server)
{
  "public_key": "YOUR_PUBLIC_KEY",
  "origin": "https://your-blog.com"
}
POST /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. Client Backend

Signs verification token via secure HMAC-SHA256 signature protocol.

3. 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).

3. API Endpoints

For custom dashboard setups, you can call our REST verification endpoints directly:

POST /api/embed/generate-key/
// Header: Content-Type: application/json
{
  "domain": "your-blog.com",
  "mode": "test"
}
GET /api/embed/validate-key/
// Parameters: key=KEY&origin=https://domain.com
// Validates test mode domain match and returns dynamic layout configs
POST /api/embed/secure-verify/
// Header: Content-Type: application/json
// Performs HMAC handshake and returns a 5-minute verified session token

4. Workflow Pipeline

Test Mode Pipeline: The script executes domain header validation on load. Upon code execution, a secure compilation query is dispatched directly to our clusters, deducting 1 credit balance.

Secure Mode Pipeline: On load, the embed dispatches a request to your backend URL. Your backend signs the verification token with your private key using HMAC-SHA256, returns the token, and verifies subsequent execution commands.

5. Custom Code Block Arguments &amp; Safety Policies

To configure sandbox initialization parameters explicitly, you can pass custom attributes directly inside your code block element markup instead of relying on the default auto-detect heuristics (which may occasionally misinterpret languages or script targets):

  • lang-name (or data-lang-name / data-lang): Specifies the programming language (e.g., python, javascript, html, c, java, rust, shell).
  • file-path / file-name (or data-file-path / data-file-name): Specifies the custom entry filename within the sandbox execution workspace (e.g., app.js, main.py).
Example: Customized HTML code block with explicit settings
<pre lang-name="python" file-path="calculator.py"><code>def add(a, b):
  return a + b
print(add(5, 7))</code></pre>

All converted code blocks are powered by a premium CodeMirror 5 workspace editor, featuring full syntax highlighting, paired bracket matching, line numbers, and a dark visual theme.

To ensure the sandboxed server workspace is always kept completely up-to-date with browser modifications, real-time auto-saving is enabled. Every change made in the editor automatically triggers a debounced (300ms) save command sent to the server WebSocket, synchronizing changes instantly before "Run Code" is even clicked.

Strict Shell Safety &amp; Execution Policies:

For container integrity and host-level protection, all dynamic sandbox runs are governed by a strict client-side execution blacklist policy. If standard server administrative instructions or system-destructive commands (e.g., sudo, apt, apt-get, or directory removals like rm -rf) are detected anywhere inside the editor pane, VM compilation is instantly aborted. The terminal console will display a crimson security alert:

Danger command present in the code: running code not permitted

6. Backend Integration Examples

Secure Mode verifies user sessions backend-to-backend via a secure HMAC-SHA256 signature protocol. Below are comprehensive frontend and backend code examples for the most popular web frameworks, structured as clean single-file examples using credentials placeholders. These examples also demonstrate where to place your Domain Ownership Verification Meta Tag inside your HTML to activate your public key.

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_PLACEHOLDER"
SECRET_KEY = "YOUR_SECRET_KEY_PLACEHOLDER"
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>
    
    <!-- 1. Domain Ownership Verification Meta Tag -->
    <meta name="embedenv-verification" content="YOUR_VERIFICATION_TOKEN_PLACEHOLDER">
</head>
<body>
    <h1>Interactive Sandbox Integration</h1>
    
    <pre lang-name="python" file-path="main.py"><code>print("Hello from python inside our sandbox!")</code></pre>

    <!-- 2. EmbedJS Dynamic SDK Loader (Secure Mode) -->
    <script 
        src="https://embedenv.com/embed.js?key=YOUR_PUBLIC_KEY_PLACEHOLDER" 
        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_PLACEHOLDER";
const SECRET_KEY = "YOUR_SECRET_KEY_PLACEHOLDER";
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>
    
    <!-- 1. Domain Ownership Verification Meta Tag -->
    <meta name="embedenv-verification" content="YOUR_VERIFICATION_TOKEN_PLACEHOLDER">
</head>
<body>
    <h1>Interactive Node.js Sandbox</h1>
    
    <pre lang-name="javascript" file-path="app.js"><code>console.log("Hello from NodeJS inside Express Sandbox!");</code></pre>

    <!-- 2. 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_PLACEHOLDER"
SECRET_KEY = "YOUR_SECRET_KEY_PLACEHOLDER"
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>
        <!-- 1. Domain Verification Meta Tag -->
        <meta name="embedenv-verification" content="YOUR_VERIFICATION_TOKEN_PLACEHOLDER">
    </head>
    <body>
        <h1>FastAPI Unified Code Sandbox</h1>
        <pre lang-name="python" file-path="script.py"><code>print("Hello from FastAPI sandboxed environment!")</code></pre>

        <!-- 2. 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 (PHP Integrated Backend/Frontend Script)
<php
// PHP Backend API Endpoint and HTML Frontend combined in a single secure file

$public_key = "YOUR_PUBLIC_KEY_PLACEHOLDER";
$secret_key = "YOUR_SECRET_KEY_PLACEHOLDER";
$django_api_url = "https://embedenv.com/api/embed/secure-verify/";

// Handle POST request verification endpoint
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 POST payload to Embedenv verify
    $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 handshake failed"]);
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PHP Embedenv Sandbox Integration</title>
    
    <!-- 1. Domain Verification Meta Tag -->
    <meta name="embedenv-verification" content="YOUR_VERIFICATION_TOKEN_PLACEHOLDER">
</head>
<body>
    <h1>PHP Integrated Script Sandbox</h1>
    
    <pre lang-name="php" file-path="script.php"><code><?php
echo "Hello from PHP VM Container!";
?></code></pre>

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