All Projects â†’ neg4n â†’ next-api-og-image

neg4n / next-api-og-image

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

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to next-api-og-image

next-api-compose
đŸ§Ŧ Simple, dependency free, error aware and powerful utility to compose chain of multiple middleware into one Next.js API Route.
Stars: ✭ 22 (-87.71%)
Mutual labels:  next, nextjs-plugin, nextjs-api-routes
personal-website
Personal website – made with Next.js, Preact, MDX, RMWC, & Vercel
Stars: ✭ 16 (-91.06%)
Mutual labels:  next, vercel
personal-website
My personal website, statically generated by Next.js
Stars: ✭ 16 (-91.06%)
Mutual labels:  next, vercel
harshhhdev.github.io
Harsh Singh's personal blog and portfolio ⚡ built with Next.js
Stars: ✭ 23 (-87.15%)
Mutual labels:  jsx, next
bradgarropy.com
🏠 my home on the web
Stars: ✭ 58 (-67.6%)
Mutual labels:  next, vercel
React-Netflix-Clone
A Fully Responsive clone of Netflix website built using React.JS as a Front-end & Firebase as a Back-end.
Stars: ✭ 91 (-49.16%)
Mutual labels:  jsx, react-hooks
next-api-decorators
Collection of decorators to create typed Next.js API routes, with easy request validation and transformation.
Stars: ✭ 187 (+4.47%)
Mutual labels:  next, vercel
Fre
đŸ‘ģ Tiny Footprint Concurrent UI library for Fiber.
Stars: ✭ 3,195 (+1684.92%)
Mutual labels:  jsx, react-hooks
next-qrcode
React hooks for generating QRCode for your next React apps.
Stars: ✭ 87 (-51.4%)
Mutual labels:  nextjs-plugin, react-hooks
next-banner
đŸ–ŧī¸ Generate Open Graph images for Next.js on build
Stars: ✭ 45 (-74.86%)
Mutual labels:  next, vercel
crud-app
❄ī¸ A simple and beautiful CRUD application built with React.
Stars: ✭ 61 (-65.92%)
Mutual labels:  jsx, react-hooks
next-share
Social media share buttons for your next React apps.
Stars: ✭ 145 (-18.99%)
Mutual labels:  next, nextjs-plugin
openzeppelin-network.js
An easy to use and reliable library that provides one line access to Web3 API.
Stars: ✭ 45 (-74.86%)
Mutual labels:  react-hooks
think
Instagram clone using React Native with funcional components, React Hooks, React Navigation 4x and Reactotron debugger
Stars: ✭ 20 (-88.83%)
Mutual labels:  react-hooks
eslint-config-typescript-unified
🛠ī¸ A unified ESLint configuration with sensible defaults for TypeScript projects.
Stars: ✭ 15 (-91.62%)
Mutual labels:  react-hooks
keystone-with-react-engine
KeystoneJS CMS with React Engine as rendering engine, so we can render backend .jsx templates
Stars: ✭ 17 (-90.5%)
Mutual labels:  jsx
coderplex-org
Official Website for Coderplex Community. Built with Next.js and deployed on Vercel.
Stars: ✭ 32 (-82.12%)
Mutual labels:  vercel
CodeSignal-Practice Solutions
No description or website provided.
Stars: ✭ 28 (-84.36%)
Mutual labels:  vercel
Nectus
A boilerplate Flask API for a Fullstack Project with some additional packages and configuration prebuilt. ⚙
Stars: ✭ 32 (-82.12%)
Mutual labels:  react-hooks
element
Fast and simple custom elements.
Stars: ✭ 65 (-63.69%)
Mutual labels:  jsx

Next.js API OG Image ¡ version types license

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:

npm i next-api-og-image chrome-aws-lambda
# or
yarn 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 [email protected] (47.6 MB)

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

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 example && npm i && npm run dev then navigate to http://localhost:3000/

Basic usage and explaination

HTML template
import { withOGImage } from 'next-api-og-image'

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

export 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
define react or html. 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 and react template provider functions
can be defined as asynchronous

Examples

HTML template
import { withOGImage } from 'next-api-og-image'

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

export 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:

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

  1. typed query strategy with query params ?foo=hello&bar=friend will look like this:
    export default withOGImage<'query', 'foo' | 'bar'>(/* ... */)
  2. typed body strategy with JSON payload { "foo": "hello", "imNested": { "bar": "friend" }} will look like this:
    export 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:

  1. Will throw an runtime error
  2. 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):

import { withOGImage } from 'next-api-og-image'

export default withOGImage({
  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 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.

export default function myTemplate({ myQueryParam }) {
  return `<h1>${myQueryParam}</h1>`
}

...or in TypeScript

import type { NextApiOgImageQuery } from 'next-api-og-image'

type QueryParams = 'myQueryParam'
export default function myTemplate({ myQueryParam }: Record<QueryParams, string>) {
  return `<h1>${myQueryParam}</h1>`
}

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):

const nextApiOgImageConfig = {
  // Values passing strategy
  strategy: '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 pixels
  width: 1200,
  // Height of the image in pixels
  height: 630,
  // 'Cache-Control' HTTP header
  cacheControl: '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 Tools
    inspectHtml: true,
    // Whether to set error message in response
    // if there are strategy related errors
    errorsInResponse: true,
  },
}

License

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].