Download the image #10
-
I've been trying to get it to work but having unfortunate errors. My import React from 'react'
import ReactDOM from 'react-dom/server'
import { withOGImage } from 'next-api-og-image'
import OGImagePreview from '@/pages/og-image-preview'
import { OGImage, Author } from '@/types/index'
const html = async ({
title,
description,
date,
readingTime,
slug,
authors,
}: Record<keyof OGImage, string | string[] | any[]>): Promise<string> => {
const el = React.createElement(OGImagePreview, {
title: title as string,
description: description as string,
date: date as string,
readingTime: readingTime as string,
slug: slug as string,
authors: authors as Author[],
})
const body = ReactDOM.renderToStaticMarkup(el)
const baseCSS = `
.font-alegreya {
font-family: Alegreya;
}
.font-jetbrains {
font-family: 'JetBrains Mono';
}
`
return `
<html>
<head>
<meta charset="utf-8" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="true" />
<link
href="https://fonts.googleapis.com/css2?family=Alegreya:wght@800&display=swap"
rel="stylesheet"
/>
<link
href="https://fonts.googleapis.com/css2?family=JetBrains+Mono&display=swap"
rel="stylesheet"
/>
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet" />
<style>${baseCSS}</style>
</head>
<body>
${body}
</body>
<script src="https://unpkg.com/tailwindcss-jit-cdn"></script>
</html>
`
}
const nextApiOgImageConfig = {
// 'Content-Type' HTTP header
contentType: 'image/png',
// 'Cache-Control' HTTP header
cacheControl: 'max-age 3600, must-revalidate',
// NOTE: Options within 'dev' object works only when process.env.NODE_ENV === 'development'
dev: {
// Whether to replace binary data (image/screenshot) with HTML
// that can be debugged in Developer Tools
inspectHtml: true,
},
html,
}
export default withOGImage<keyof OGImage>(nextApiOgImageConfig) How do I download the image itself? I was trying to use simple import ky from 'ky'
import {
getAllEssays,
getAllTutorials,
getAllSnippets,
getAllTips,
getEssayBySlug,
getTutorialBySlug,
getSnippetBySlug,
getTipBySlug,
} from '@/utils/mdx'
import { siteMetadata } from '@/_data/index'
const { siteUrl } = siteMetadata
export const generateOGImage = () => {
try {
const essays = getAllEssays()
const tutorials = getAllTutorials()
const snippets = getAllSnippets()
const tips = getAllTips()
essays.forEach(async ({ slug }) => {
const { meta, code } = await getEssayBySlug(slug)
const { title, description = '', date, readingTime, authors } = meta
let data = new URLSearchParams()
data.append('title', title)
data.append('description', description)
data.append('date', JSON.stringify(date))
data.append('readingTime', JSON.stringify(readingTime))
data.append('slug', slug)
data.append('authors', JSON.stringify(authors))
const options = {
method: `POST`,
body: data,
}
fetch(`${siteUrl}/api/og-image`, options)
.then((data) => {
if (!data.ok) throw data
console.log(data.body)
})
.catch((error) => {
console.error(error)
})
const json = await ky
.post('api/og-image', {
prefixUrl: siteUrl,
json: {
title: meta.title,
description: meta.description,
date: meta.date,
readingTime: meta.readingTime,
},
})
.json()
console.log(json)
})
} catch (e) {
console.error(e)
} finally {
}
} I want the image from this API to be downloaded. How do I do it? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 11 replies
-
You can try something like that: In api route ( import { withOGImage } from "next-api-og-image";
export default withOGImage({
template: { html: ({ test }) => `<h1>${test}</h1>` },
dev: { inspectHtml: false },
}); then in regular Next.js page ( import fetch from "isomorphic-unfetch";
export default function TestPage({ image }) {
const src = `data:image/png;base64,${image}`;
return (
<div>
<img src={src} />
</div>
);
}
export async function getStaticProps() {
const response = await fetch(
"http://localhost:3000/api/ogimage?test=populated%20at%20build%20time"
);
const arrayBuffer = await response.arrayBuffer();
const base64 = Buffer.from(arrayBuffer, "base64").toString("base64");
return {
props: {
image: base64,
},
};
} Navigating to |
Beta Was this translation helpful? Give feedback.
You can try something like that:
In api route (
pages/api/ogimage.js
):then in regular Next.js page (
pages/test.js
):