Metadata and OG Images in Next.js – SEO, Shareability, and Dynamic Generation

Next.js provides powerful tools for defining metadata and Open Graph (OG) images to improve SEO and social sharing. This article explains how to use static and dynamic metadata, special files like favicon and opengraph-image, and generate OG images using JSX and CSS with ImageResponse.

metadataOpen Graph imagegenerateMetadataImageResponse

~2 دقیقه مطالعه · آخرین به‌روزرسانی ۳ آبان ۱۴۰۴

Introducing Metadata in Next.js


Next.js automatically generates <head> tags using metadata APIs. These tags improve SEO and social sharing and can be inspected in browser dev tools.


Default Meta Tags


Two meta tags are always included:

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />

Static Metadata


Export a metadata object from a layout or page file to define static metadata:

// app/blog/layout.tsx
export const metadata = {
  title: 'My Blog',
  description: '...',
}

Dynamic Metadata with generateMetadata


Use generateMetadata to fetch metadata based on route data:

// app/blog/[slug]/page.tsx
export async function generateMetadata({ params }) {
  const post = await fetch(`https://api.vercel.app/blog/${params.slug}`).then(res => res.json())
  return {
    title: post.title,
    description: post.description,
  }
}

Streaming Metadata


Next.js streams metadata separately for dynamic pages, allowing UI to render first. This is disabled for bots like Twitterbot and Bingbot to ensure metadata appears in <head>.


Memoizing Data Requests


Use React’s cache to avoid duplicate fetches for metadata and page content:

// app/lib/data.ts
export const getPost = cache(async (slug) => {
  return await db.query.posts.findFirst({ where: eq(posts.slug, slug) })
})

Special Metadata Files


  • favicon.ico – browser tab icon
  • opengraph-image.jpg – OG image for social sharing
  • robots.txt – search engine indexing rules
  • sitemap.xml – site map for SEO

Static Open Graph Images


Add opengraph-image.jpg to the app folder or route-specific folders. Specific images override global ones.


Generating Dynamic OG Images


Use ImageResponse to generate OG images with JSX and CSS:

// app/blog/[slug]/opengraph-image.tsx
import { ImageResponse } from 'next/og'
import { getPost } from '@/app/lib/data'

export const size = { width: 1200, height: 630 }
export const contentType = 'image/png'

export default async function Image({ params }) {
  const post = await getPost(params.slug)
  return new ImageResponse(
    <div style={{
      fontSize: 128,
      background: 'white',
      width: '100%',
      height: '100%',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
    }}>
      {post.title}
    </div>
  )
}

ImageResponse supports flexbox, custom fonts, text wrapping, and nested images. Advanced layouts like grid are not supported.


Conclusion


Metadata and OG images in Next.js enhance SEO and social sharing. With generateMetadata and ImageResponse, you can create dynamic, precise metadata and visuals tailored to each route.


نوشته و پژوهش‌شده توسط دکتر شاهین صیامی

مقالات مرتبط

Advanced Client-Side Routing and Performance Hooks in Next.js

Next.js provides a rich set of client-side hooks and caching utilities that empower developers to build dynamic, responsive, and secure applications. From reading route parameters to tracking navigation state and reporting performance metrics, this guide walks you through the most important tools available in the App Router.

ادامه

Handling Authorization and Caching in Next.js: A Developer’s Guide

Next.js introduces powerful experimental features for access control and smart caching. This guide covers the unauthorized() function for custom 401 handling, unstable_cache for persistent memoization, updateTag for instant cache invalidation, and useLinkStatus for inline navigation feedback. Learn how to use these tools to build secure, performant, and responsive applications.

ادامه

redirect and refresh in Next.js — Smart Redirects and Client Refreshing via Server Actions

The redirect function in Next.js allows you to navigate users to a new route, returning either a 307 or 303 HTTP response depending on context. It works in Server Components, Client Components, Route Handlers, and Server Actions. The refresh function is used exclusively within Server Actions to refresh the client router. This article explains how both functions work, with practical examples and key considerations.

ادامه

NextRequest and NextResponse in Next.js — Managing Cookies, Headers, Redirects, and Rewrites

Next.js extends the native Web Request and Response APIs with NextRequest and NextResponse, offering powerful tools for managing cookies, headers, redirects, rewrites, and JSON responses. These utilities simplify server-side logic and improve control over routing, personalization, and security. This guide walks through their capabilities with practical examples and best practices.

ادامه

headers, ImageResponse, notFound, and permanentRedirect in Next.js — Request Handling, Dynamic Images, Errors, and Redirects

Next.js offers powerful tools for handling HTTP requests and responses in Server Components. The headers function lets you read incoming request headers. ImageResponse allows you to generate dynamic images using JSX and CSS. The notFound function renders a custom 404 page, and permanentRedirect enables permanent redirection to another route. This article explains how to use each feature with practical examples.

ادامه

A Complete Guide to Using metadata and generateMetadata in Next.js

In modern versions of Next.js, managing page metadata is more powerful and intuitive than ever. Metadata is automatically injected into the <head> of your pages and plays a vital role in SEO, social sharing, and user experience. This guide explains the two main ways to define metadata: using the static metadata object and the dynamic generateMetadata function.

ادامه