0
0
NextJSframework~30 mins

Dynamic OG images in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Dynamic OG Images with Next.js
📖 Scenario: You are building a blog website using Next.js. You want to create dynamic Open Graph (OG) images for each blog post. These images will show the post title and author name on a styled background. This helps your posts look great when shared on social media.
🎯 Goal: Build a Next.js API route that generates a dynamic OG image using the @vercel/og library. The image should display the blog post's title and author name with styled text on a colored background.
📋 What You'll Learn
Create a Next.js API route file named pages/api/og.js
Set up the data for a blog post with exact title and author
Add a configuration variable for image size
Use the @vercel/og library to create an image response with the post data
Return the generated image as the API response
💡 Why This Matters
🌍 Real World
Dynamic OG images improve social media sharing by showing customized images for each blog post, increasing click-through rates and engagement.
💼 Career
Understanding how to generate dynamic images on the server is valuable for frontend and full-stack developers working with modern web frameworks like Next.js.
Progress0 / 4 steps
1
Set up blog post data
Create a constant object called post with these exact properties: title set to "Learn Next.js OG Images" and author set to "Jane Doe".
NextJS
Need a hint?

Use const post = { title: "Learn Next.js OG Images", author: "Jane Doe" }

2
Add image size configuration
Create a constant called imageSize and set it to an object with width 1200 and height 630.
NextJS
Need a hint?

Use const imageSize = { width: 1200, height: 630 }

3
Create the OG image API route
Import ImageResponse from @vercel/og. Export a default async function called handler that returns a new ImageResponse with a div containing the post title in an h1 and the author in a p. Use imageSize.width and imageSize.height for the image size.
NextJS
Need a hint?

Use ImageResponse to create the image with a styled div containing the post title and author.

4
Complete the API route export
Add the config export with runtime set to 'edge' to enable the API route to run at the edge.
NextJS
Need a hint?

Add export const config = { runtime: 'edge' } at the end of the file.