Guides
Code Embed
Run your own HTML, CSS and JavaScript on your site inside a sealed frame, with your site's colours handed to your code. For site owners who write web code.
What it is
Code Embed is a block that runs HTML, CSS and JavaScript you write. Your code runs on your site inside a sealed frame: an iframe with sandbox="allow-scripts" and a content policy that allows only inline code. The frame gets the colours and the light or dark scheme of the ground it sits on, and its own size. A section background also hears where the mouse is over it and where text lies over it, as boxes and colours. It gets nothing else from the page.
Use it for visual code: a canvas drawing, an animated diagram, a small interactive piece. For a video, a map or any embed that loads from a URL, use the Embed block.
The block is on every plan. nertia does not check your code. Frame content is not page content for search engines.
Add one
- In the editor, press Add.
- In Building blocks, choose Code Embed. It sits directly after Embed. On a phone, tap it, then tap Insert.
- Select the block. The Element panel shows a Code row with the bytes used in each field and one button: Add code on an empty block, Open code editor once it holds code.
- The Code editor opens with three tabs: HTML, CSS and JavaScript. Write your code, then press Save & close. The block on the canvas starts again with the new code. Typing alone changes nothing on the canvas.
The code editor always shows this notice:
This runs your code on your site. nertia does not check it. It runs in a sealed frame: it cannot read the page, cookies or what visitors type, and it cannot load anything from the web.
Closing the editor with changes you have not saved asks whether to save or discard them.
The other controls in the Element panel, for a block in flow (a section background has fewer, see Section background):
- Height: 240, 360, 480 or 640 CSS pixels, or Screen for the full height of the window. A height wins over the aspect ratio.
- Aspect ratio: 16:9, 4:3, 1:1 or 3:1. It applies when Height is set to use the aspect ratio. The block is always the full width of its container.
- Title for screen readers: the frame's accessible name. See A title is required to publish.
- Fallback image: a still picture shown whenever the code is not running. Without an image the box stays empty.
- Fallback image on phones: shown instead of the fallback image on screens narrower than 700 pixels. Leave it empty and phones get the fallback image.
- Fallback image in dark mode: shown instead of the fallback image when the site is dark. Leave it empty and the fallback image shows in both.
- Fallback image on phones in dark mode: shown on screens narrower than 700 pixels when the site is dark. It is used only when Fallback image in dark mode is set; leave it empty and phones get the dark fallback image.
- Fallback image description: the fallback picture's alt text.
- Reduced motion: Show the fallback when motion is reduced is the default. Choose My code handles reduced motion to run your code for visitors who ask for less motion and read the flag yourself.
The box is sized before the code runs, so the page never shifts. The frame never resizes the page. The frame starts after the page first paints, once the block is within one screen of the visible area.
What your code gets
The frame document holds your CSS in the head, your HTML in the body and your JavaScript after it. Before your code runs, nertia adds a small helper, window.nertia:
nertia.env: the latest environment, ornulluntil the first one arrives.nertia.onEnv(fn): callsfn(env)now if an environment has arrived, and again when the visitor's operating system switches between light and dark, when the box resizes, when the block scrolls in or out of view, when the tab is hidden or shown, and when the visitor's reduced motion setting changes. In the editor it also fires when you switch the preview between light and dark, change a style or change the page.
env holds:
scheme:lightordark, read from the background of the ground the frame sits on, such as the band behind it.palette: the colours painted where the frame sits, with the keysbackground,foreground,muted,mutedForeground,border,accentandaccentForeground. A band with its own fill reports its own colours.reducedMotion:truewhen the visitor asks for less motion.widthandheight: the box size in CSS pixels.visible:falsewhen the block is off screen or the tab is hidden.
The helper also sets the palette on <html> as CSS variables, so your CSS can use the site's colours directly: --background, --foreground, --muted, --muted-foreground, --border, --accent, --accent-foreground. It sets data-scheme (light or dark) and data-reduced-motion (true or false) on <html>. When reduced motion is on, it adds one rule that stops CSS animations and transitions. It does not stop requestAnimationFrame: your JavaScript reads env.reducedMotion for that.
html and body start with no margin, the full height of the box, a transparent background and hidden overflow. Text in the frame uses the browser's default font unless your code sets one. The site's fonts are not available; to use a font file, inline it as a data: URL.
The environment, the palette and the CSS variables arrive with the first env. Code that reads them before onEnv first calls back gets nothing, so read them inside onEnv, as this example does. A canvas that fills with the site's accent colour and redraws when anything changes:
<canvas id="art"></canvas>
#art { display: block; width: 100%; height: 100%; }
const canvas = document.getElementById('art');
const ctx = canvas.getContext('2d');
nertia.onEnv((env) => {
const ratio = window.devicePixelRatio || 1;
canvas.width = Math.round(env.width * ratio);
canvas.height = Math.round(env.height * ratio);
const accent = getComputedStyle(document.documentElement).getPropertyValue('--accent').trim();
ctx.fillStyle = accent;
ctx.fillRect(0, 0, canvas.width, canvas.height);
});
Section background
A Code Embed can be a section's background. It fills the section and sits under the section's content.
- Select a section. In its panel, press Add background code in the Background code row.
- nertia adds a Code Embed as the section's background and selects it. To write its code, press the code button on the block's toolbar (its name is Open code editor), or Add code in its Code row.
A section has one background. Once it has one, the Background code row shows the block's name as Layers shows it, and pressing it selects the block. A second one is refused with This section already has background code. A background cannot be duplicated: a section has one.
A background is decoration. It takes no clicks and no keyboard focus, and the frame is hidden from screen readers, so it has no title. A background needs no title to publish; a block in flow that holds code does.
Because it takes no clicks on the canvas, you reach a background from the section's Background code row or from Layers.
A block is a background only when it is added as one, as Add background code does. A Code Embed added from Add runs in flow, and a Code Embed inside a column always runs in flow.
A background's panel shows the Code row, Extend, Fallback image, Fallback image on phones, Fallback image in dark mode, Fallback image on phones in dark mode, Fallback image description and Reduced motion. It has no height, aspect ratio or title: the frame takes the size of its section.
Extend has two choices: This section, the default, and Up to the top of the page. With Up to the top of the page, the frame reaches from the top of the page to the bottom of its section, and env.width and env.height are the extended layer's, not the section's. The frame shows only where nothing above it paints: a band, a section, or the page around them with its own fill, gradient or image covers it.
A background hears two things a block in flow does not:
nertia.onPointer(fn): callsfnwith{ type: 'pointer', x, y }when the mouse moves, withxandyfrom 0 to 1 across the frame. When the pointer leaves the frame's area or the page, or is not a mouse,fngets{ type: 'pointer', x: null }once. Touch and pen positions are not sent. It calls back no more than once per animation frame. When your code runs under reduced motion, the pointer is still sent; your code decides what to do with it.nertia.onZones(fn): callsfnwith{ type: 'zones', zones }. Each zone is{ x, y, w, h, color }: the box the text covers, in fractions of the frame, and the text's computed CSS colour. There is one zone per text colour per block whose text lies over the frame, at most 64; past that the largest are kept. Zones hold geometry and colours, never the text. They are sent after each environment update while the frame is visible. Text on a part of a block that paints its own solid fill, such as a filled button, is not reported.
A block in flow never calls these two: its frame takes the mouse itself.
In the editor, a block can show a notice. Visitors never see these notices. A block in flow shows a bar along its bottom edge. A background shows a small pill at its section's bottom corner, above the content.
- A script error or an unhandled promise rejection in the frame shows
Script error:and the message, the first 300 characters of it. The frame keeps running. The editor shows the first error a frame reports. - A paused block shows Run code. Nothing is wrong with the code: the site's code is paused in this browser. See When code is paused.
- When code is switched off for the site, the block shows
Code is switched off for this site. It does not run here or on the published site.Nothing is wrong with the code: code is switched off for the whole site.
Limits
Sizes are UTF-8 bytes.
- HTML: 16 KB per block.
- CSS: 16 KB per block.
- JavaScript: 64 KB per block.
- Code per page, all blocks together: 128 KB.
- Running frames per page: 4. A fifth block on the page shows its fallback.
The Element panel's Code row counts the bytes in each field and warns from 90 percent of a field's limit. In the code editor, a field's count turns red once the field is over its limit. Saving past a limit is refused with the count.
What it cannot do
The frame has its own blank origin and a content policy that allows only inline code. Your code:
- Cannot read or change the page around it.
- Has no cookies or storage of the site, and cannot reach them.
- Cannot fetch or load from the web: no
fetch, XHR, WebSocket or EventSource, and no script, stylesheet, font or image from a URL. Images, media and fonts work as inlinedata:orblob:URLs. - Cannot run
evalornew Function. - Cannot open popups or new windows.
- Cannot show
alert,confirmorprompt. - Cannot navigate the page to an address.
- Cannot submit a form.
- Cannot link out. A link that loads a new document in the frame ends the block: it shows its fallback until the page is reloaded or its code changes.
- Gets no camera, microphone, location, clipboard or fullscreen.
Third-party script-tag widgets, such as chat bubbles, tracking pixels and form vendors, do not work in Code Embed. The Embed block is for embeds by URL.
What it still can
Some things a browser does not let the page block. Your code, and anyone who reads it, should know them.
- Send its own frame to another address. On a nertia page the address must be a host on nertia's embed list, such as a video or booking host. The block usually ends when the frame loads that address: the frame is removed and the fallback shows. Code that leaves before its own document has finished loading makes that host's page the frame's document, and it stays until the frame next loads.
- Use the visitor's processor. While the block is on screen, your code can run a heavy loop or shader. In some browsers that slows the whole page. Browsers slow down off-screen frames on their own.
- Move the tab's history, in Safari and Firefox. Your code can call
history.back(),history.forward()orhistory.go(n). That can send the visitor back to the site they came from. It cannot name an address. Chromium browsers block this. See When code is paused. - Open a WebRTC connection. Your code can exchange data with a server of your own over WebRTC, and that server sees the visitor's IP address.
- Two gaps in Safari. WebAssembly compiles although the frame's policy asks for it to be blocked. A
preconnecthint can open a connection to any host, without sending a request.
None of these lets your code read the page, the site or what a visitor types elsewhere on the page.
When code is paused
nertia watches for a page that is left right after code starts. If a page is left within 5 seconds of a frame starting, before the visitor taps, clicks or presses a key, the site's code is paused in that browser for 10 minutes. Each time it happens again the pause doubles, up to one day. The pause ends on its own when its time runs out; nothing a visitor does on the site clears it sooner. The first healthy page view after it ends resets the doubling.
- In Safari and Firefox, code that moves the history within the site's own pages pauses the site's code at once, whenever it happens.
- While code is paused, visitors see the fallback.
- In the editor, the block shows the fallback with
Code is paused. This page left right after the code started last time.and a Run code button. Press it to clear the pause and start the code. - A visitor who closes the tab within 5 seconds without touching the page sees the fallback for 10 minutes if they come back.
- Private windows keep storage for the session, so the pause applies there too. Only a browser that blocks storage outright remembers nothing from one page view to the next, and there the pause does not apply.
nertia can also turn code off for a site. While it is off, every Code Embed block shows its fallback and the code editor says Code is turned off on this site. Contact nertia to turn it back on.
Who can write code
Anyone who can edit the site writes code, in the code editor, with Save & close. Owners, managers and editors all can.
- No connector tool can write code. A tool that tries is refused and told to add the code in the editor.
- In the editor's chat, the assistant can propose a Code Embed, new or for a block that exists. You see the code on a card with two buttons, Run this code and Cancel. Nothing is written until you press Run this code.
- The card shows, in a box, the code each field gets. It names any field whose code it removes, and the fields it leaves as they are. Pressing Run this code writes the code in those boxes and the card's title, removes what the card says it removes, and sets the block's height or aspect ratio when the assistant chose one. A field the card does not show or name is left as it is.
- If the block changed after the card was shown, for example because a teammate saved code into it, the card is refused and nothing is written. Ask again in chat.
- Chat writes at most 16 KB of code in total, across HTML, CSS and JavaScript. Paste larger code in the code editor, where the limits above apply.
- A card expires 10 minutes after it is shown. After that, ask again.
- Only the person who asked can press their card, and only from the editor in a browser.
- If nertia has turned code off for the site, chat cannot propose code.
- The sealed frame rules above apply to code from a card exactly as to code you type: what it cannot read and cannot load.
- Saved sections, templates and imports keep the Code Embed block, its settings and its fallback, and arrive with the code left out. An import says so.
- Undo and Redo in the editor never bring code back: a block they bring back is empty. That includes undoing a chat turn. To bring back earlier code, open History and press Restore this version.
- Pressing Run this code adds nothing to Undo. Undo puts the page's blocks back as they were before the step it undoes: a block added after that point goes, with its code, and code on blocks that stay is left as it is. To take code off a block, clear it in the code editor.
- An undo or restore made with a CLI token cannot bring code back.
- Rolling back a release can bring back code that a person applied earlier and later removed.
In an exported site
Exporting a site keeps its Code Embed code. Nothing is stripped: the files the export downloads hold every block's HTML, CSS and JavaScript as they are on the site.
A project scaffolded from the file with create-nersh runs that code, each block in the same sealed frame as on nertia. The scaffold installs the block from nertia's registry with the site's other sections, and its app/page.tsx passes codeEmbed="run" to SiteRenderer. That takes @nersh/render 0.4.0 or later, in a project made with create-nersh 0.4.0 or later.
- To turn the code off, remove the prop or pass
codeEmbed="off". Off is the default: every Code Embed then shows its fallback. renderSiteToHtmlnever runs code: the static HTML it writes holds each block's reserved box and its fallback picture, if it has one, and no frame and none of the code.- nertia's off switches do not reach an exported project. When nertia turns code off for a site, or for every site, a project scaffolded from that site keeps running its code. The exported site is yours, and the
codeEmbedprop decides. - The project sends a
Content-Security-Policyheader with aframe-srclist, set innext.config.ts, and writes the same rule as a<meta http-equiv="Content-Security-Policy">tag inapp/layout.tsx, for static hosts andoutput: "export", which ignore the header. It lets embeds from the listed hosts load, and it limits where a sealed frame can send itself: only to a host on that list, as What it still can describes. If you embed from other hosts, add them to both lists. - In an app of your own that passes
codeEmbed="run"and sends noframe-src: without this rule, a frame's code can send the frame to any site. That site's page then shows in the block's box, has the network, and can stay there. Whatever a frame loads, it still cannot read your page, its cookies or its storage, and cannot navigate the top window, open popups or submit forms.
The block and its host come from the registry, so these work as they do on nertia: the sealed frame and everything in What it cannot do, the nertia helper with onEnv, and section backgrounds with onPointer and onZones. So do the HTML, CSS and JavaScript limits per block (a block over one shows its fallback), the 4 running frames per page, and the pause in When code is paused, kept per browser.
An exported project has no nertia editor. There is no code editor, the editor's notices do not show, and no check asks for a title before the site goes live. The code is in site.json, in copy, under the block's <instanceId>.html, <instanceId>.css and <instanceId>.js keys: change it there. The 128 KB per page is checked when nertia saves code, not in an exported project. Give every block that holds code a title in its <instanceId>.title key, for screen readers.
Importing a site file into nertia leaves the code out. The block, its settings and its fallback stay; its HTML, CSS and JavaScript come in empty. When the file held code, nertia says Code Embed code was left out. Add it again in the code editor. in the chat of a new site made from the file, and in the Replace this site? question when the file replaces a site. Add the code again in the code editor.
A title is required to publish
A frame without a title is announced to screen reader users only as "frame". Publishing a site with a Code Embed block that holds code and has an empty Title for screen readers is refused with a message that names the page, for example: "Code Embed on the home page needs a title before you publish. Screen readers read it out." Write a short description of what the block shows.