Home > software_development > How to Render Open Graph Image (og-image) in NextJs - App Router

How to Render Open Graph Image (og-image) in NextJs - App Router

Open-graph enhances an article or video link when it is shared on social media. It shows the featured-image/thumbnail, title, description, and the URL.

By :Thomas Inyang🕒 16 Jun 2024

og-image-nextjs

What is an Open Graph Image?

Open Graph images (og:image) are a critical component of modern web sharing. When users share your website link on social media platforms like Facebook, Twitter, LinkedIn, or messaging apps like WhatsApp and Telegram, the Open Graph image is the preview image that appears alongside your content.

Why Open Graph Images Matter

Including properly configured Open Graph images in your Next.js application provides several important benefits:

  1. Higher Engagement: Eye-catching images grab attention in crowded social feeds
  2. Brand Recognition: Consistent visual styling reinforces your brand identity
  3. Improved Context: Visual previews help users understand what they'll find when clicking
  4. Professional Appearance: Properly formatted images look polished and trustworthy
  5. Increased Click-Through Rates: Quality preview images can dramatically improve CTR

Without proper Open Graph images, social platforms may randomly select images from your page resulting in missed opportunities to engage potential visitors.

See Also: How to Use Google Analytics in NextJs.

This guide will focus on the most flexible approach: dynamically generating Open Graph images using Next.js' App Router.

How to render og-image in NextJs.

Using one of the conventions stated in the docs to set Open Graph and Twitter images for a route segment.


If the NextJs (App route) project is blog-styled - with dynamic routing [slug] or [id] folder.

That is, app/post/[slug], create a file "opengraph-image.tsx" in the [slug] folder and the final routing will be "app/content/[slug]/opengraph-image.tsx".


Copy this line of codes into the file.

import { ImageResponse } from "next/og";
export const runtime = "edge";
export const alt = "About Post";

//Resize the dimension of the image
export const size = {
width: 320,
height: 320,
};

export const contentType = "image/*";
export default async function Image({ params }: { params: { slug: string } }) {

//use your content endpoint here.
// const post = await fetch(`post endpoint`).then((res) =>
// res.json()
// )
return new ImageResponse(
(
<div
style={{
fontSize: 32,
background: "white",
width: "100%",
height: "100%",
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
{post.title}
</div>
),
{
...size,
}
);
}


Touch "app/post/[slug]/page.jsx" to generate dynamic metadata that will include the openGraph props and it should look like this.

export async function generateMetadata({ params, searchParams }, parent) {

// read route params
const slug = params.slug;

//Use your post content endpoint here
const post = await fetchBySlug(slug);

// optionally access and extend

const previousImages = (await parent).openGraph?.images || [];
return {
title: post.title,
openGraph: {
description: post.excerpt,
title: post.title,
images: `${post.featured_image}` //if your post content does not have a featured image, you can use any image URL,
},
};
}


For a page file with .tsx extension in [slug] folder.

import type { Metadata, ResolvingMetadata } from 'next'

type Props = {
params: { id: string }
searchParams: { [key: string]: string | string[] | undefined }
}

export async function generateMetadata(
{ params, searchParams }: Props,
parent: ResolvingMetadata
): Promise<Metadata> {

// read route params
const id = params.id

// fetch data
const post = await fetch(`your post url`).then((res) => res.json())

// optionally access and extend (rather than replace) parent metadata
const previousImages = (await parent).openGraph?.images || []

return {
title: post.title,
description: post.excerpt,
openGraph: {
title: post.title,
images: `${post.featured_image}`
//if your post content does not have a featured image, you can use any image URL,
},
}
}

Save and run. To check the implementation, click on ":" at the top of the browser and click "share".

See Also: How to Use Isometric Icons in NextJs App.

This implementation creates a visually appealing Open Graph image with the post title, an excerpt, author information, and publication date.

Conclusion

Implementing dynamic Open Graph images in your Next.js application is a small investment that can yield significant returns in terms of social sharing engagement and click-through rates. The techniques outlined in this guide allow you to:


1. Create visually compelling previews that represent your content accurately

2. Maintain brand consistency across social platforms

3. Dynamically generate images that reflect the actual content

4. Optimize for different social media platforms automatically.


By following these best practices, your content will stand out in crowded social feeds and messaging apps, driving more traffic to your Next.js application.


Remember that Open Graph images are often the first impression users have of your content—make it count!

Please Share

console.logHello

You may also like