Download a returned screenshot safely
This local example validates status and streams the asset. Production systems should also restrict allowed asset origins and use their storage adapter.
import { createWriteStream } from "node:fs";
import { pipeline } from "node:stream/promises";
import { Readable } from "node:stream";
const captureResponse = await fetch(
"https://api.prod.ss.snapshot-site.com/api/v1/screenshot",
{
method: "POST",
headers: {
"Content-Type": "application/json",
"x-snapshotsiteapi-key": process.env.SNAPSHOT_SITE_API_KEY,
},
body: JSON.stringify({
url: "https://example.com",
format: "webp",
width: 1440,
height: 900,
fullSize: true,
}),
},
);
if (!captureResponse.ok) throw new Error("Capture failed");
const capture = await captureResponse.json();
if (!capture.link) throw new Error("Missing artifact link");
const assetResponse = await fetch(capture.link);
if (!assetResponse.ok || !assetResponse.body) {
throw new Error("Artifact download failed");
}
await pipeline(
Readable.fromWeb(assetResponse.body),
createWriteStream("./capture.webp"),
);
