Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

:bowtie: Easy way to generate open-graph images dynamically in HTML or React using Next.js API Routes. Suitable for serverless environment.

License

NotificationsYou must be signed in to change notification settings

neg4n/next-api-og-image

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

84 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Simple library with purpose of providing easy way to dynamically
generate open-graph images usingNext.js API routes.

If you're not familiar with dynamic open-graph images concept - please seevercel/og-image repository's README for very detailed explaination.

you can treat this project as simpler and configurable version of mentioned earliervercel repository

Features

  • 🐄 Super easy usage
  • 🌐 Suitable forserverless environment
  • :bowtie: Elegant way for defining templates both inReact andHTML
  • 📬 Multiple strategies - pass values by GET and query params or POST and JSON body
  • 🥷 TypeScript compatible

Installing

In yourNext.js project, execute:

npm i next-api-og-image chrome-aws-lambda# oryarn 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 onVercel(50MB), you may want to install older versions ofchrome-aws-lambda

In order to do so, replacechrome-aws-lambda(while adding the dependencies) withchrome-aws-lambda@6.0.0(47.6 MB)

Please, refer to#23 (comment) for more info 🙏

Examples

You can find more examples here:

theexample/ directory contains simpleNext.js application implementingnext-api-og-image . To fully explore examples implemented in it by yourself - simply donpm link && cd example && npm i && npm run dev then navigate tohttp://localhost:3000/

Basic usage and explaination

HTML template
import{withOGImage}from'next-api-og-image'exportdefaultwithOGImage({template:{html:({ myQueryParam})=>`<h1>${myQueryParam}</h1>`}})
React template
import{withOGImage}from'next-api-og-image'exportdefaultwithOGImage({template:{react:({ myQueryParam})=><h1>{myQueryParam}</h1>}})

Creating template

You've may noticed thehtml andreact properties in configuration. Their responsibility is to provide HTML document to image creator(browser screenshot), filled with your values.

⚠️ NOTE
Templatecannot be ambigious. You must either
definereact orhtml. Never both at once

Specification

Thehtml andreact properties are template providers functions. Each function's first (and only) parameter is nothing else butHTTP 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 isobject destructuring.

⚠️ NOTE
html andreact template provider functions
can be defined as asynchronous

Examples

HTML template
import{withOGImage}from'next-api-og-image'exportdefaultwithOGImage({template:{html:({ myQueryParam})=>`<h1>${myQueryParam}</h1>`}})
React template
import{withOGImage}from'next-api-og-image'exportdefaultwithOGImage({template:{react:({ myQueryParam})=><h1>{myQueryParam}</h1>}})

if you send GET HTTP request toapi 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:

  1. 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.

  2. 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 bystrategy prop in the configuration. Default strategy isquery.

⚠️ 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 thingstyped. Well... its actually super easy! Simply add generic types towithOGImage function.

  1. typedquery strategy with query params?foo=hello&bar=friend will look like this:
    exportdefaultwithOGImage<'query','foo'|'bar'>(/* ... */)
  2. typedbody strategy with JSON payload{ "foo": "hello", "imNested": { "bar": "friend" }} will look like this:
    exportdefaultwithOGImage<'body',{foo:string,imNested:{bar:string}}>({strategy:'body',/* ... */})

Errors

When strategy is set toquery and you're sending POST HTTP request with JSON body or when strategy is set tobody and you're sending GET HTTP request with query params -next-api-og-image will:

  1. Will throw an runtime error
  2. Set appropiate response message to the clientYou can disable this behaviour by settingdev: { 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 tohook configuration property. The only parameter isNextApiRequest object withimage attached to it.

example (JavaScript):

import{withOGImage}from'next-api-og-image'exportdefaultwithOGImage({template:{react:({ myQueryParam})=><div>🔥{myQueryParam}</div>,},dev:{inspectHtml:false,},hook:(innerRequest)=>{console.log(innerRequest.image)// will print the generated image on the server as Buffer},})

Splitting files

Keeping all the templates inline withinNext.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 likemy-template.html.js ormy-template.js when you define template as react(naming convention is fully up to you) with code e.g.

exportdefaultfunctionmyTemplate({ myQueryParam}){return`<h1>${myQueryParam}</h1>`}

...or in TypeScript

importtype{NextApiOgImageQuery}from'next-api-og-image'typeQueryParams='myQueryParam'exportdefaultfunctionmyTemplate({ myQueryParam}:Record<QueryParams,string>){return`<h1>${myQueryParam}</h1>`}

then importing it and embedding in thewithOGImage.

Loading custom local fonts

In order to load custom fonts from the project source, you need to create source file with your font inbase64 format or simply bind the font file content to the variable in yourNext.js API route

Configuration

Apart fromhtml andreact configuration property (intemplate)(whose are required), you can specify additional info about hownext-api-og-image should behave.

Example configuration withdefault values(apart from template.html or template.react prop):

constnextApiOgImageConfig={// Values passing strategystrategy:'query',// Response's 'Content-Type' HTTP header and browser screenshot type.type:'png',// Screenshot's quality. WORKS ONLY IF 'type' IS SET TO 'jpeg'quality:90,// Width of the image in pixelswidth:1200,// Height of the image in pixelsheight:630,// 'Cache-Control' HTTP headercacheControl:'max-age 3600, must-revalidate',// Hook function that allows to intercept inner NextApiRequest with `ogImage` prop attached.// useful for e.g. saving image in the database after the generation.// The hook function return is Map containing custom headers that will be set BEFORE sending// response to the client.hook:null,// NOTE: Options within 'chrome' object only works when next-api-og-image is run in server (not serverless!!) environment.chrome:{// Custom command-line args passed to the browser start command// by default, no arguments are provided.args:null,// Custom executable provided. Useful when you e.g. have to run Chromium instead of Google Chrome// by default, executable is retrieved automatically (it looks for Google Chrome in the filesystem)executable:null,}// 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 ToolsinspectHtml:true,// Whether to set error message in response// if there are strategy related errorserrorsInResponse:true,},}

License

This project is licensed under the MIT license.
All contributions are welcome.


[8]ページ先頭

©2009-2025 Movatter.jp