Next.js API OG Image
Simple library with purpose of providing easy way to dynamically
generate open-graph images using Next.js API routes.
Features
Installing
npm i next-api-og-image -S
yarn add next-api-og-image
Basic usage and explaination
import { withOGImage } from 'next-api-og-image'
export default withOGImage({ html: ({ myQueryParam }) => `<h1>${myQueryParam}</h1>` })
The Next.js API route where this code exists will open headless browser
on each request sent, put HTML content in the web page, screenshot it and return as binary data. The parameter of the function bound to html
in the configuration object is nothing else but request query parameters. This allows you to create HTML templates.
if you send GET HTTP request to api route with code presented above e.g. localhost:3000/api/foo?myQueryParam=hello
- it will render heading with content equal to 'hello'
Configuration
Apart from html
configuration property (which is required), you can specify Content-Type and Cache-Control headers!
Example configuration with default values (apart from required html prop):
const nextApiOgImageConfig = {
contentType: 'image/png',
cacheControl: 'max-age 3600, must-revalidate'
}
Examples
You can find more examples here:
the example/
directory contains simple Next.js application implementing next-api-og-image
. To fully explore examples implemented in it by yourself - simply do npm link && cd examples && npm i && npm run dev
then navigate to http://localhost:3000/
License
This project is licensed under the MIT license.
All contributions are welcome.