forked from
leaflet.pub/leaflet
a tool for shared writing and social publishing
1import { headers } from "next/headers";
2
3export async function getMicroLinkOgImage(
4 path: string,
5 options?: {
6 width?: number;
7 height?: number;
8 deviceScaleFactor?: number;
9 noCache?: boolean;
10 },
11) {
12 const headersList = await headers();
13 let hostname = headersList.get("x-forwarded-host");
14 let protocol = headersList.get("x-forwarded-proto");
15 if (process.env.NODE_ENV === "development") {
16 protocol === "https";
17 hostname = "leaflet.pub";
18 }
19 let full_path = `${protocol}://${hostname}${path}`;
20 return getWebpageImage(full_path, {
21 ...options,
22 setJavaScriptEnabled: false,
23 });
24}
25
26export async function getWebpageImage(
27 url: string,
28 options?: {
29 setJavaScriptEnabled?: boolean;
30 width?: number;
31 height?: number;
32 deviceScaleFactor?: number;
33 noCache?: boolean;
34 },
35) {
36 let response = await fetch(
37 `https://api.cloudflare.com/client/v4/accounts/${process.env.CLOUDFLARE_ACCOUNT}/browser-rendering/screenshot`,
38 {
39 method: "POST",
40 headers: {
41 "Content-type": "application/json",
42 Authorization: `Bearer ${process.env.CLOUDFLARE_API_TOKEN}`,
43 },
44 body: JSON.stringify({
45 url,
46 setJavaScriptEnabled: options?.setJavaScriptEnabled,
47 scrollPage: true,
48 addStyleTag: [
49 {
50 content: `* {scrollbar-width:none; }`,
51 },
52 ],
53 gotoOptions: {
54 waitUntil: "load",
55 },
56 viewport: {
57 width: options?.width || 1400,
58 height: options?.height || 733,
59 deviceScaleFactor: options?.deviceScaleFactor,
60 },
61 }),
62 next: !options?.noCache
63 ? undefined
64 : {
65 revalidate: 600,
66 },
67 },
68 );
69
70 return response;
71}