1.0.2 • Published 1 year ago
next-auto-og-image v1.0.2
next-auto-og-image
Automatically generate and update Open Graph (OG) images for Next.js projects using page screenshots.
Code
Find the code at github.com/lpolish/next-auto-og-image
Features
- Automatically generates OG images for all pages in your Next.js project
 - Uses actual page screenshots for accurate representation
 - Integrates seamlessly with Next.js App Router
 - Updates OG images during the build process
 
Installation
Install the package using npm:
npm install next-auto-og-imageUsage
- Update your 
next.config.jsfile to include the plugin: 
const withAutoOGImage = require('next-auto-og-image/next-plugin')
/** @type {import('next').NextConfig} */
const nextConfig = {
  // Your existing Next.js config
}
module.exports = withAutoOGImage(nextConfig)- In your 
app/layout.tsxfile, use thegetOGImageMetadatafunction: 
import { Metadata } from 'next'
import { getOGImageMetadata } from 'next-auto-og-image'
export async function generateMetadata(): Promise<Metadata> {
  const ogImageMetadata = await getOGImageMetadata('app/layout.tsx')
  
  return {
    ...ogImageMetadata,
    // Add any other metadata here
  }
}
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  )
}- For individual pages, add the following to each 
page.tsxfile: 
import { Metadata } from 'next'
import { getOGImageMetadata } from 'next-auto-og-image'
export async function generateMetadata(): Promise<Metadata> {
  const ogImageMetadata = await getOGImageMetadata('app/example/page.tsx')
  
  return {
    ...ogImageMetadata,
    // Add any other metadata here, or override the OG image if needed
    // openGraph: {
    //   images: [{ url: '/custom-image.png', width: 1200, height: 630 }],
    // },
  }
}
export default function ExamplePage() {
  return <h1>Example Page</h1>
}How it works
- During the build process, the plugin starts a development server.
 - It then scans your 
appdirectory for all page files. - For each page, it generates a screenshot using Puppeteer.
 - The screenshots are saved in the 
public/og-imagesdirectory. - The 
getOGImageMetadatafunction provides the correct metadata for each page. 
Configuration
Currently, the package uses default settings for OG image generation. Future versions may include customization options.
Requirements
- Next.js 13.0.0 or higher
 - Node.js 14.0.0 or higher
 
Limitations
- The development server needs to be able to render your pages correctly for accurate screenshots.
 - Pages with dynamic content may not be represented accurately in the OG images.
 
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License.