:bowtie: Easy way to generate open-graph images dynamically in HTML or React using Next.js API Routes. Suitable for serverless environment. Easy way to generate open-graph images dynamically in HTML or React using Next.js API Routes. Suitable for serverless environment.
Installations
npm install next-api-og-image
Developer Guide
Typescript
Yes
Module System
CommonJS
Node Version
17.7.0
NPM Version
8.5.2
Releases
Ability to set custom chrome options
Published on 21 Sept 2022
Add dynamic chrome options for lambda & non lambda
Published on 13 Sept 2022
Fix chrome path on Windows 64bit
Published on 29 Jul 2022
Ability to set custom headers
Published on 26 Jul 2022
Hook function
Published on 11 Jul 2022
Move chrome-aws-lambda to peerDependencies
Published on 11 Apr 2022
Contributors
Unable to fetch Contributors
Languages
TypeScript (84.31%)
JavaScript (15.69%)
Developer
Download Statistics
Total Downloads
103,488
Last Day
14
Last Week
127
Last Month
389
Last Year
15,501
GitHub Statistics
216 Stars
84 Commits
18 Forks
1 Watching
8 Branches
4 Contributors
Bundle Size
349.60 kB
Minified
102.87 kB
Minified + Gzipped
Package Meta Information
Latest Version
4.3.0
Package Id
next-api-og-image@4.3.0
Unpacked Size
91.20 kB
Size
16.92 kB
File Count
12
NPM Version
8.5.2
Node Version
17.7.0
Total Downloads
Cumulative downloads
Total Downloads
103,488
Last day
75%
14
Compared to previous day
Last week
24.5%
127
Compared to previous week
Last month
-50.4%
389
Compared to previous month
Last year
-39.7%
15,501
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
4
Peer Dependencies
4
Next.js API OG Image ·
Simple library with purpose of providing easy way to dynamically
generate open-graph images using Next.js API routes.
If you're not familiar with dynamic open-graph images concept - please see vercel/og-image repository's README for very detailed explaination.
you can treat this project as simpler and configurable version of mentioned earlier vercel repository
Features
- 🐄 Super easy usage
- 🌐 Suitable for serverless environment
- :bowtie: Elegant way for defining templates both in React and HTML
- 📬 Multiple strategies - pass values by GET and query params or POST and JSON body
- 🥷 TypeScript compatible
Installing
In your Next.js project, execute:
1npm i next-api-og-image chrome-aws-lambda 2# or 3yarn add next-api-og-image chrome-aws-lambda
Short note about the peer dependencies
ℹ️ If your serverless function does not fit in the allowed size frames on Vercel (50MB), you may want to install older versions of
chrome-aws-lambda
In order to do so, replace chrome-aws-lambda
(while adding the dependencies) with chrome-aws-lambda@6.0.0
(47.6 MB)
Please, refer to https://github.com/neg4n/next-api-og-image/issues/23#issuecomment-1090319079 for more info 🙏
Examples
You can find more examples here:
- JavaScript
- TypeScript
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 example && npm i && npm run dev
then navigate to http://localhost:3000/
Basic usage and explaination
HTML template
1import { withOGImage } from 'next-api-og-image' 2 3export default withOGImage({ template: { html: ({ myQueryParam }) => `<h1>${myQueryParam}</h1>` } })
React template
1import { withOGImage } from 'next-api-og-image' 2 3export default withOGImage({ template: { react: ({ myQueryParam }) => <h1>{myQueryParam}</h1> } })
Creating template
You've may noticed the html
and react
properties in configuration. Their responsibility is to provide HTML document to image creator (browser screenshot), filled with your values.
⚠️ NOTE
Template cannot be ambigious. You must either
definereact
orhtml
. Never both at once
Specification
The html
and react
properties are template providers functions. Each function's first (and only) parameter is nothing else but HTTP request's query params converted to object notation.
This allows you to create fully customized HTML templates by simply accessing these parameters. The preferred way to do that is object destructuring.
⚠️ NOTE
html
andreact
template provider functions
can be defined as asynchronous
Examples
HTML template
1import { withOGImage } from 'next-api-og-image' 2 3export default withOGImage({ template: { html: ({ myQueryParam }) => `<h1>${myQueryParam}</h1>` } })
React template
1import { withOGImage } from 'next-api-og-image' 2 3export default withOGImage({ template: { react: ({ myQueryParam }) => <h1>{myQueryParam}</h1> } })
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'
Strategies
next-api-og-image
allows you to choose strategy for providing values to the template. The available strategies are:
-
query
(default) - values are passed by query params and GET HTTP request.
These values ⛔️ cannot be nested nor accessed by nested destructuring in template provider function. -
body
- values are passed by POST HTTP request and JSON body.
These values ✅ can be nested and accessed by nested destructuring in template provider function.
The strategies are determined by strategy
prop in the configuration. Default strategy is query
.
⚠️ NOTE
Regardless of the strategy - all properties (every single one)
are implicitly casted to string, even very long JSON's nested values
Types in template provider function
If you're using TypeScript, you probably want to have these things
typed. Well... its actually super easy! Simply add generic types to withOGImage
function.
- typed
query
strategy with query params?foo=hello&bar=friend
will look like this:1export default withOGImage<'query', 'foo' | 'bar'>(/* ... */)
- typed
body
strategy with JSON payload{ "foo": "hello", "imNested": { "bar": "friend" }}
will look like this:1export default withOGImage<'body', { foo: string, imNested: { bar: string } }>({ strategy: 'body', /* ... */ })
Errors
When strategy is set to query
and you're sending POST HTTP request with JSON body or when strategy is set to body
and you're sending GET HTTP request with query params - next-api-og-image
will:
- Will throw an runtime error
- Set appropiate response message to the client
You can disable this behaviour by setting
dev: { errorsInResponse: false }
in the configuration
Hooking the post-generate process
In some scenarios you may want to do something (in other words - execute some logic) after generation of the image.
This can be easily done by providing function to hook
configuration property. The only parameter is NextApiRequest
object with image
attached to it.
example (JavaScript):
1import { withOGImage } from 'next-api-og-image' 2 3export default withOGImage({ 4 template: { 5 react: ({ myQueryParam }) => <div>🔥 {myQueryParam}</div>, 6 }, 7 dev: { 8 inspectHtml: false, 9 }, 10 hook: (innerRequest) => { 11 console.log(innerRequest.image) 12 // will print the generated image on the server as Buffer 13 }, 14})
Splitting files
Keeping all the templates inline within Next.js API route should not be problematic, but if you prefer keeping things in separate files you can follow the common pattern of creating files like my-template.html.js
or my-template.js
when you define template as react (naming convention is fully up to you) with code e.g.
1export default function myTemplate({ myQueryParam }) { 2 return `<h1>${myQueryParam}</h1>` 3}
...or in TypeScript
1import type { NextApiOgImageQuery } from 'next-api-og-image' 2 3type QueryParams = 'myQueryParam' 4export default function myTemplate({ myQueryParam }: Record<QueryParams, string>) { 5 return `<h1>${myQueryParam}</h1>` 6}
then importing it and embedding in the withOGImage
.
Loading custom local fonts
In order to load custom fonts from the project source, you need to create source file with your font in base64 format or simply bind the font file content to the variable in your Next.js API route
Configuration
Apart from html
and react
configuration property (in template
) (whose are required), you can specify additional info about how next-api-og-image
should behave.
Example configuration with default values (apart from template.html or template.react prop):
1const nextApiOgImageConfig = { 2 // Values passing strategy 3 strategy: 'query', 4 // Response's 'Content-Type' HTTP header and browser screenshot type. 5 type: 'png', 6 // Screenshot's quality. WORKS ONLY IF 'type' IS SET TO 'jpeg' 7 quality: 90, 8 // Width of the image in pixels 9 width: 1200, 10 // Height of the image in pixels 11 height: 630, 12 // 'Cache-Control' HTTP header 13 cacheControl: 'max-age 3600, must-revalidate', 14 // Hook function that allows to intercept inner NextApiRequest with `ogImage` prop attached. 15 // useful for e.g. saving image in the database after the generation. 16 // The hook function return is Map containing custom headers that will be set BEFORE sending 17 // response to the client. 18 hook: null, 19 // NOTE: Options within 'chrome' object only works when next-api-og-image is run in server (not serverless!!) environment. 20 chrome: { 21 // Custom command-line args passed to the browser start command 22 // by default, no arguments are provided. 23 args: null, 24 // Custom executable provided. Useful when you e.g. have to run Chromium instead of Google Chrome 25 // by default, executable is retrieved automatically (it looks for Google Chrome in the filesystem) 26 executable: null, 27 } 28 // NOTE: Options within 'dev' object works only when process.env.NODE_ENV === 'development' 29 dev: { 30 // Whether to replace binary data (image/screenshot) with HTML 31 // that can be debugged in Developer Tools 32 inspectHtml: true, 33 // Whether to set error message in response 34 // if there are strategy related errors 35 errorsInResponse: true, 36 }, 37}
License
This project is licensed under the MIT license.
All contributions are welcome.
No vulnerabilities found.
No security vulnerabilities found.
Other packages similar to next-api-og-image
next-api-og-image-sparticuz
Easy way to generate open-graph images dynamically using Next.js API Routes.
qmatias-next-api-og-image
Easy way to generate open-graph images dynamically using Next.js API Routes.
@snelsi/next-api-og-image
Easy way to generate open-graph images dynamically using Next.js API Routes.
megasanjay-next-api-og-image
Easy way to generate open-graph images dynamically using Next.js API Routes.