To render it to a PNG, use Sharp, which draws SVG with librsvg:
import sharp from 'sharp'const png = await sharp(Buffer.from(svg)).png().toBuffer()
Under the hood, it handles layout calculation, font, typography and more, to generate a SVG that matches the exact same HTML and CSS in a browser.
Documentation
JSX
Satori only accepts JSX elements that are pure and stateless. You can use a subset of HTML
elements (see section below), or custom React components, but React APIs such as useState and useEffect are not supported, and dangerouslySetInnerHTML is only supported on <style> and <script>.
Experimental: builtin JSX support
Satori has an experimental JSX runtime that you can use without having to install React. You can enable it on a per-file basis with @jsxImportSource pragmas. In the future, it will autocomplete only the subset of HTML elements and CSS properties that Satori supports for better type-safety.
If you don't have JSX transpiler enabled, you can simply pass React-elements-like objects that have type, props.children and props.style (and other properties too) directly:
Satori supports a limited subset of HTML and CSS features, due to its special use cases. In general, only these static and visible elements and properties that are implemented.
For example, the cursor CSS property is not in consideration. Text inputs show their value or placeholder, styled with ::placeholder, button inputs their label, and selects their selected option, or their options with multiple or size, but other form controls have no content. <style> elements apply their CSS, see Stylesheets, but external resources via <link> or <script> aren't loaded.
Also, Satori does not guarantee that the SVG will 100% match the browser-rendered HTML output since Satori implements its own layout engine based on the SVG 1.1 spec.
You can find the list of supported HTML elements and their preset styles here.
Images
You can use <img> to embed images. However, width, and height attributes are recommended to set:
When using background-image, the image will be stretched to fit the element by default if you don't specify the size.
If you want to render the generated SVG to another image format such as PNG, it would be better to use base64 encoded image data (or buffer) directly as props.src so no extra I/O is needed in Satori:
Note: This is experimental and may change or be removed in any release. It's only available from satori/experimental, so it doesn't add to the size of the satori import.
With satori/experimental, you can draw the content of a <canvas> with WebGL2 via the webgl prop. Satori calls it with a WebGL2 context sized to the canvas, then embeds what you drew as an image:
Each canvas gets a new WebGL2 context, which is destroyed with everything drawn into it afterwards:
In browsers and Web Workers, Satori uses OffscreenCanvas.
In Node.js 20.16+, Satori loads the gl package from your project, which must be a WebGL2 build of headless-gl such as an ANGLE + SwiftShader one (e.g. github:encharm/headless-gl). It runs shaders on the CPU. If you bundle your server code, keep gl external and include its files in the deployment.
To provide contexts yourself, e.g. to reuse them across renders, pass a createWebGLContext(width, height) option that returns a WebGL2 context. Satori doesn't destroy the contexts it returns.
The width and height attributes set the drawing buffer size (300×150 by default), like in browsers. The canvas is displayed at its CSS size, keeping that aspect ratio unless both CSS dimensions are set.
Before calling webgl, Satori binds the default framebuffer, sets the viewport to the whole drawing buffer, and clears it to transparent, like a new canvas. Afterwards, it reads the default framebuffer. The webgl callback can be async.
The drawing buffer is treated as premultiplied alpha unless the context was created with premultipliedAlpha: false.
Children of <canvas> are fallback content and are not rendered.
The satori import ignores the webgl prop and draws <canvas> like any other element.
If you use React's JSX types, add the webgl prop to them:
import type { WebGLCanvasRenderer } from 'satori/experimental'declare module 'react' { interface CanvasHTMLAttributes<T> { webgl?: WebGLCanvasRenderer }}
CSS
Satori uses Taffy to lay out Flexbox, Grid and block layouts, and its own inline layout for text and inline elements. It’s not a complete CSS implementation, but it supports most common CSS features. Properties marked “Supported” behave as in browsers; otherwise, the differences are listed:
Supported, with these differences: table, ruby and their inner values, and two-value syntax like inline flow-root, aren't supported and throw. Form controls have no default styles, except selects, which have the ones of Chrome.
position
Positioned inline elements (with display: inline) aren't the containing block of their absolutely positioned descendants, the nearest positioned block is. Sticky inline elements aren't moved.
Note:
In 3D transforms, elements in a preserve-3d context are drawn back to front by the depth of their centers, and elements that intersect aren't cut where they cross. Perspective is approximated: each element is drawn with the affine transform closest to it around its center, which is exact for elements facing the viewer, such as translateZ(). satori/experimentaldraws perspective exactly.
Percentages in calc(), min(), max() and clamp() only work in sizes, margins, paddings, insets, gaps, flexBasis and translations. Elsewhere, values with them are ignored.
Properties that aren't listed are ignored, for example columns, writingMode and fontStretch.
Invalid values in inline styles throw an error, which fails the whole render, unless they're ignored with onStyleError. Stylesheets drop them instead, see Stylesheets.
inherit on properties that aren't inherited, e.g. border: inherit, sets their initial value instead of the value of the parent.
Stylesheets
The CSS of <style> elements applies to the whole tree, including the elements of components. The declarations of matching rules are merged with inline styles in cascade order, so the table above applies to them too. Selectors, specificity, !important, nesting, @layer, @media, @supports, @container, @property and the media attribute are supported, with these differences:
@media matches the width and height of the image, on a static screen in light mode, e.g. prefers-color-scheme: light and hover: none.
@container supports size queries, but style() and scroll-state() queries don't match. Container units like cqw are supported, but in values of custom properties, they're of the viewport.
@property sets the initial values of custom properties and whether they're inherited, but values aren't checked or computed with its syntax.
Invalid and unsupported declarations are dropped like in browsers, and passed to onStyleError. Values with var() are only checked when they're computed, where invalid values throw like in inline styles.
@supports checks declarations the same way, but properties that Satori ignores count as supported. selector() is supported, but not font-tech() and font-format().
::before and ::after are supported, with content made of strings, attr(), counter(), counters(), quotes and url(). Quotes are always “ and ”, as quotes isn't supported. Other pseudo-elements, such as ::marker and ::first-line, aren't supported, so rules with them don't apply.
Pseudo-classes of interactions such as :hover never match, and functional pseudo-classes other than :is(), :where(), :not(), :has(), :nth-*() and :lang() make their rule invalid.
Other at-rules are ignored, such as @font-face, @keyframes, @scope and @import.
Perspective (experimental)
Note: This is experimental and may change or be removed in any release. It's only available from satori/experimental, so it doesn't add to the size of the satori import.
With satori/experimental, perspective from the perspective property and the perspective() function is drawn exactly:
SVG has no perspective transforms, so each element with perspective is split into triangles that are each drawn with an affine transform, within 0.5px of the exact position. This makes the SVG larger and slower to render: depending on the angle, an element is drawn up to a few hundred times.
Language and Typography
OpenType Features: Satori supports advanced typography features via HarfBuzz text shaping. Use the font-feature-settings CSS property to enable OpenType features such as:
Ligatures (liga, dlig, hlig)
Small caps (smcp, c2sc)
Stylistic sets (ss01-ss20)
Contextual alternates (calt)
Swashes (swsh, cswh)
And many more OpenType features
Example:
<div style={{ fontFeatureSettings: '"smcp" 1, "liga" 0' }}> This Text Uses Small Caps</div>
HarfBuzz also improves glyph shaping for complex scripts such as Arabic. Words
are ordered with a simplified Unicode bidirectional algorithm, so right-to-left
text in a left-to-right element, and left-to-right text and numbers in a
right-to-left one, follow browser ordering, and lines with direction: rtl are
laid out from the right. Explicit embeddings with unicodeBidi, bracket pairs
and reordering text with inline elements in it aren't supported yet.
Fonts
Satori supports four font formats: TTF, OTF, WOFF and WOFF2. Variable fonts are rendered as their default instance, e.g. the regular weight. You must specify the font if any text is rendered with Satori, and pass the font data as ArrayBuffer (web) or Buffer (Node.js):
Multiple fonts can be passed to Satori and used in fontFamily.
[!TIP]
We recommend you define global fonts instead of creating a new object and pass it to satori for better performance, if your fonts do not change. Read it for more detail
Emojis
To render custom images for specific graphemes, you can use graphemeImages option to map the grapheme to an image source:
The image will be resized to the current font-size (both width and height) as a square.
Locales
Satori supports rendering text in different locales. You can specify the supported locales via the lang attribute:
await satori( <div lang="ja-JP">骨</div>)
Same characters can be rendered differently in different locales, you can specify the locale when necessary to force it to render with a specific font and locale. Check out this example to learn more.
Supported locales are exported as the Locale enum type.
Dynamically Load Emojis and Fonts
Satori supports dynamically loading emoji images (grapheme pictures) and fonts. The loadAdditionalAsset function will be called when a text segment is rendered but missing the image or font:
await satori( <div>👋 你好</div>, { // `code` will be the detected language code, `emoji` if it's an Emoji, or `unknown` if not able to tell. // `segment` will be the content to render. loadAdditionalAsset: async (code: string, segment: string) => { if (code === 'emoji') { // if segment is an emoji return `data:image/svg+xml;base64,...` } // if segment is normal text return loadFontFromSystem(code) } })
Runtime Support
Satori can be directly used in browser, Node.js (>= 16), and Web Workers. It bundles its underlying WASM dependencies as base64-encoded strings and loads them at runtime.
If there is a limitation on dynamically loading WASM (e.g. Cloudflare Workers), you can use the Standalone Build which is mentioned below.
Standalone Build of Satori
Satori's standalone build doesn't include the WASM binary of its layout engine by default, and you need to load it manually before using Satori.
First, you need to download the layout.wasm binary from Satori build and provide it yourself. Let's use fetch to load it directly from the CDN as an example:
import satori, { init } from 'satori/standalone'const res = await fetch('https://unpkg.com/satori/layout.wasm')const layoutWasm = await res.arrayBuffer()await init(layoutWasm)// Now you can use satori as usualconst svg = await satori(...)
Of course, you can also load the layout.wasm file from your local disk via fs.readFile in Node.js or other methods.
Font Embedding
By default, Satori renders the text as <path> in SVG, instead of <text>. That means it embeds the font path data as inlined information, so succeeding processes (e.g. render the SVG on another platform) don’t need to deal with font files anymore.
You can turn off this behavior by setting embedFont to false, and Satori will use <text> instead:
Set pointScaleFactor to control how layout values are rounded to the pixel grid: they are rounded to multiples of 1 / pointScaleFactor px, or not rounded with 0. It defaults to 1, and higher values improve rendering precision on high-DPI displays. The width of text is rounded up the same way, so that it fits.
By default, an invalid or unsupported declaration in an inline style throws an error, which fails the whole render. With onStyleError, the declaration is ignored instead, and its error is passed to the callback. Declarations of stylesheets are always dropped, like in browsers, and passed to the callback too:
Colors in gradients are converted either way. SVG interpolates gradients in sRGB, so Satori adds stops to gradients that are interpolated in another color space: those with a color space like linear-gradient(in oklch, red, blue), and those in Oklab by default because they have colors from lab(), lch(), oklab(), oklch(), color(), color-mix() or relative colors.
Debug
To draw the bounding box for debugging, you can pass debug: true as an option:
A float in the middle of a paragraph is placed at the start of the paragraph, instead of on the line it's in. Each line is shortened by the floats beside its top, so a line that is taller than its text can overlap a float that starts lower. lineClamp, textOverflow: ellipsis and textWrap don't apply to text after a float.
zIndex
Supported
visibility
Supported
color
Colors that SVG renderers may not support are converted to rgb() and rgba(), see Colors. Colors outside the sRGB gamut, like color(display-p3 1 0 0), are clipped to it. light-dark() always uses the light color, since color-scheme isn't supported. System colors like Canvas aren't supported.
margin
marginTop
Supported
marginRight
Supported
marginBottom
Supported
marginLeft
Supported
Position
top
Supported
right
Supported
bottom
Supported
left
Supported
inset
Supported
Size
width
Supported. fit-content() is also supported, which Chrome doesn't support yet
height
Supported. fit-content() is also supported, which Chrome doesn't support yet
aspectRatio
Supported
Min & max size
minWidth
fit-content and stretch are ignored. fit-content() with a length is supported, which Chrome doesn't support yet
minHeight
min-content, max-content, fit-content and stretch are ignored
maxWidth
fit-content and stretch are ignored. fit-content() with a length is supported, which Chrome doesn't support yet
maxHeight
min-content, max-content, fit-content and stretch are ignored
border
Width (borderWidth, borderTopWidth, ...)
Supported
Style (borderStyle, borderTopStyle, ...)
On rounded corners, dots are spaced evenly along each side, while Chrome draws square dots on the straight parts of thick dotted borders
Side shorthands (cornerTopShape, cornerRightShape, ...)
Supported
Flex
flexDirection
Supported
flexWrap
Supported
flexGrow
Supported
flexShrink
Supported
flexBasis
Supported
alignItems
Supported
alignContent
Supported
alignSelf
Supported
justifyContent
Supported
gap, rowGap, columnGap
Supported
order
Supported
Grid
gridTemplateColumns, gridTemplateRows
Supported except for subgrid, which throws, and masonry
gridTemplateAreas
Supported
gridAutoColumns, gridAutoRows
Supported
gridAutoFlow
Supported
gridRow, gridColumn, gridArea and their longhands
Supported
justifyItems, justifySelf
Supported
placeItems, placeContent, placeSelf
Supported
Shorthands (grid, gridTemplate)
Supported
List
listStyleType
The Chinese, Japanese, Korean and Ethiopic counter styles, symbols() and names of @counter-style rules are drawn like decimal. Markers can't be styled, since ::marker isn't supported
listStylePosition
Supported
listStyleImage
Only url() is supported, not gradients
Shorthand (listStyle)
Supported
counterReset, counterIncrement, counterSet
Counters other than list-item aren't displayed, since content and counter() aren't supported. Where a marker is placed, and how many items a reversed() counter counts, are found from the style prop and the default styles of elements, not their tw classes
Font
fontFamily
Only the fonts passed in the fonts option are used. After the listed families, the other loaded fonts are used as fallbacks in the order they were passed, so generic families like serif don't select a font
Applied with the OpenType features of the font. Small caps aren't synthesized when the font has none, fontVariantAlternates only supports historical-forms, since @font-feature-values isn't supported, and fontVariantEmoji has no effect
Text
direction
Also set by the dir attribute, except for auto. With rtl, flex rows, grid columns, block boxes and lines of text start at the right. Lines with inline elements in them are aligned, but their content isn't reordered yet. unicodeBidi isn't supported
tabSize
Supported
textAlign
start and end follow direction. match-parent isn't supported
textIndent
Supported except for the hanging and each-line keywords
verticalAlign
middle, top, bottom, text-top and text-bottom only apply to images and other atomic inlines, not to inline elements
textTransform
Supported. full-width and full-size-kana are also supported, which Chrome doesn't support yet
textOverflow
ellipsis only applies to text without inline elements in it
textDecoration
Decorations are drawn per element: textDecoration: none on a descendant removes the parent's lines, and a descendant's own decoration replaces them instead of adding to them. textUnderlinePosition isn't supported
Only applies to text without inline elements in it. This is also true for WebkitLineClamp, which applies with display: -webkit-box and WebkitBoxOrient: vertical