@magnet-js/ssr
v0.2.0
Published
Server-side rendering support for Magnet components.
Readme
@magnet/ssr
Lightweight server-side rendering support for Magnet components.
@magnet/ssr exports ssrWindow, a minimal implementation of MagnetWindow
that renders Magnet components to plain HTML strings on the server. It provides
lightweight server-side DOM implementations (SSRComment, SSRText,
SSRElement) with just enough surface area for the rest of Magnet to operate.
Install
JSR
deno add jsr:@magnet/ssrnpm via JSR
npx jsr add @magnet/ssrnpm
npm install @magnet-js/ssrUsage
import { ssrWindow } from "@magnet/ssr";
import { magnet } from "@magnet/ui";
const ctx = magnet({ window: ssrWindow /* signal API */ });
const element = ctx.html.div({ class: "greeting" }, "Hello");
console.log(element.toString());
// <div class="greeting">Hello</div>If you need a full document, prepend <!DOCTYPE html> yourself:
const html = "<!DOCTYPE html>" + element.toString();Namespaced attributes
Consumers specify namespaced attributes by wrapping the value with a namespace
URI key from @magnet/ui:
import { nsAttr } from "@magnet/ui";
const xlink = nsAttr("http://www.w3.org/1999/xlink");
const element = ctx.html.svg({
"x:href": xlink("/icon.svg"),
});The consumer is responsible for choosing a prefixed key such as "x:href" in
the attributes object. nsAttr attaches the namespace URI to the value. Magnet
passes both the prefixed key and the namespace URI to setAttributeNS, so
ssr.ts stores the attribute under the full key name.
Design trade-offs
The implementation is intentionally minimal and fast:
- No attribute value escaping. Consumers are expected to provide well-formed attribute values.
- Empty string attributes render as boolean attributes. For example,
disabled=""is emitted asdisabled. - Namespaced attributes are stored by their full key. The consumer chooses a
prefixed key such as
"x:href";nsAttrattaches the namespace URI to the value, and Magnet passes both the key and the URI tosetAttributeNS. - Shadow DOM is not supported.
attachShadowis stubbed out. Magnet checksbrowser()before attaching shadow roots, so this path is not exercised during SSR. - No attribute name validation. Invalid or unsafe attribute names are emitted as-is.
- Text nodes escape
&,<, and>only. This is sufficient for plain text content; consumers handling richer text should preprocess it.
License
MIT © 2026 Fernando G. Vilar.
