I have an NextJS app and I’m trying to implement an API for response an OG Image in PNG format.
I use satori
for generate SVG data and @resvg/resvg-wasm
for convert SVG to PNG format.
Here is my code
import OgImageTemplate from "@/components/OgImageTemplate";
import satori from "satori";
import { Resvg, initWasm } from "@resvg/resvg-wasm";
export const runtime = "edge";
export default async function handler(req) {
const fontRegular = await fetch(
"https://cdn.jsdelivr.net/fontsource/fonts/poppins@latest/latin-400-normal.ttf"
).then((res) => res.arrayBuffer());
const fontBold = await fetch(
"https://cdn.jsdelivr.net/fontsource/fonts/poppins@latest/latin-600-normal.ttf"
).then((res) => res.arrayBuffer());
const decodedUrl = req.url.replace(/&%3B/g, "&");
const { searchParams } = new URL(decodedUrl);
const title = searchParams.get("title");
const sub = searchParams.get("sub");
const ogImage = await satori(<OgImageTemplate title={title} sub={sub} />, {
width: 1200,
height: 630,
fonts: [
{
name: "Poppins",
data: fontRegular,
weight: 400,
style: "normal",
},
{
name: "Poppins",
data: fontBold,
weight: 600,
style: "normal",
},
],
});
const wasmResponse = await fetch("https://unpkg.com/@resvg/[email protected]/index_bg.wasm");
const wasmArrayBuffer = await wasmResponse.arrayBuffer();
try {
await initWasm(wasmArrayBuffer);
const resvg = new Resvg(ogImage, {
font: {
loadSystemFonts: false,
},
});
const pngData = resvg.render();
const pngBuffer = pngData.asPng();
return new Response(pngBuffer, {
status: 200,
headers: {
"Content-Type": "image/png",
},
});
} catch (error) {
console.error("Resvg wasm not initialized => ", error);
return new Response("Resvg wasm not initialized", { status: 500 });
}
}
I deployed to Cloudflare Pages succeed, but when I access the API, it show the error
"logs": [
{
"message": [
"Resvg wasm not initialized => ",
"CompileError: WebAssembly.instantiate(): Wasm code generation disallowed by embedder"
],
"level": "error",
"timestamp": 1709448024156
}
],
The function initWasm
throw this error and I searched all around the internet and still do not know how to fix this.
Do anyone know the solution for this ?
Thanks a lot