How to Set an Open Graph Image in React
Set the `og:image` tag for React pages, deliver route-specific metadata to crawlers, and debug missing or stale link previews.

To set an Open Graph image in React, put a <meta property="og:image" content="..."> tag in the document head. The image URL should be publicly accessible, and the tag needs to be present in the HTML delivered for the page you share. For route-specific previews, provide the metadata in server-rendered or prerendered HTML instead of relying only on a client-side update.
Open Graph metadata tells services that fetch a page how to represent it in a shared link preview. The browser’s Elements panel can show a tag added after JavaScript runs, while a crawler that reads only the original response may never see it. Next.js documents that some crawlers, including facebookexternalhit, cannot execute JavaScript; this is why the raw response matters. See the React meta reference and the Next.js metadata guide.
1. Choose how your React app delivers metadata
The right implementation depends on whether your app uses Next.js App Router, another server-rendering or prerendering setup, or a client-rendered single-page application (SPA). The key requirement is the same: the shared URL’s response should contain the correct metadata for that route.

| App setup | Recommended approach | What to verify |
|---|---|---|
| Next.js App Router | Metadata API or opengraph-image file convention |
Route-specific metadata in the response HTML |
| React with server rendering or prerendering | Render the tags into the server or prerendered document head | Each public route has its own correct tags |
| Client-rendered SPA | Add server rendering, prerendering, or equivalent metadata delivery for shareable routes | The raw HTML has tags before client JavaScript runs |
React’s <meta> component can be rendered from within the React tree and is placed in the document head. That makes it convenient to compose metadata with components, but it does not establish that a third-party crawler executes the application and waits for a client-side update. For SPA-only metadata, inspect the response before assuming a preview crawler will receive it. See the React documentation.
2. Add the Open Graph tags in React
For a page whose HTML is rendered on the server or generated ahead of time, render a complete set of tags. Replace the example values with the title, description, canonical page URL, and image URL for that route.
export default function ArticleMetadata() {
return (
<>
<meta property="og:title" content="A page title" />
<meta
property="og:description"
content="A short description of this page."
/>
<meta
property="og:url"
content="https://example.com/articles/example"
/>
<meta property="og:type" content="article" />
<meta
property="og:image"
content="https://example.com/images/example-share.jpg"
/>
</>
)
}
Use an absolute image URL so a preview service can fetch the image without resolving a path against an unexpected base URL. Make sure the page URL in og:url identifies the shared page, rather than reusing one URL across unrelated routes. The image should depict the page’s content and be accessible to the crawler; a tag pointing to a private or unavailable image cannot produce the intended preview.
With server rendering or prerendering, the component must be included in the render for the specific route. A plain React SPA can render this component after navigation, but that alone may leave the initial server response without the route’s metadata. Select the rendering approach based on the hosting and routing stack; there is no single recipe that fits every React deployment.
3. Set metadata with the Next.js App Router
In Next.js App Router, export a metadata object for static values or a generateMetadata function for values that depend on route data. Put the export in a Server Component, such as the relevant page.tsx or layout. The metadata API supports image URLs with optional dimensions and alt text.
import type { Metadata } from 'next'
export const metadata: Metadata = {
openGraph: {
title: 'Example page',
description: 'A useful description of this page.',
url: 'https://example.com/example',
type: 'article',
images: [
{
url: 'https://example.com/images/example-share.jpg',
width: 1200,
height: 630,
alt: 'A description of the image',
},
],
},
}
export default function Page() {
return <main><h1>Example page</h1></main>
}
For a dynamic route, load that route’s data and return its metadata. This example assumes a getArticle function that retrieves the article; implement it using your own data source.
import type { Metadata } from 'next'
type Props = { params: Promise<{ slug: string }> }
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params
const article = await getArticle(slug)
return {
openGraph: {
title: article.title,
description: article.description,
url: `https://example.com/articles/${slug}`,
type: 'article',
images: [{
url: article.shareImageUrl,
width: 1200,
height: 630,
alt: article.shareImageAlt,
}],
},
}
}
Adapt the parameter type and data-loading code to your Next.js version and route. The important part is that the metadata comes from the same page-specific record as the page itself. If an article has no custom share image, choose a deliberate default rather than allowing an unrelated route image to slip through.
Metadata inheritance can replace a parent Open Graph object
Next.js metadata is composed through layouts and pages. If a child route defines its own openGraph object, it replaces the parent’s entire openGraph object; it does not automatically merge each property. A child that sets only an image may therefore lose a title or description provided by the parent. Repeat or spread the shared fields intentionally, then set the route-specific values. Consult the current metadata guide for the documented behavior.
4. Use Next.js’s Open Graph image file convention
When an image belongs naturally to a route segment, place a supported image file named opengraph-image in that segment. Next.js emits the corresponding metadata automatically. A deeper route’s image takes precedence over one in a higher-level segment. Supported static file extensions include JPG, JPEG, PNG, and GIF.

app/
articles/
example/
page.tsx
opengraph-image.jpg
opengraph-image.alt.txt
Put a concise image description in opengraph-image.alt.txt next to the image when you want to supply alt text. For a generated image, add an opengraph-image.tsx route that returns an image response. The generated route can use route parameters; Next.js documents that generated images are statically optimized by default unless they depend on request-time APIs or uncached data. See the Open Graph image file convention reference.
| Option | Use it when | Trade-off |
|---|---|---|
metadata or generateMetadata |
You need explicit control of URLs, dimensions, alt text, or data-derived fields | You own the image URL and metadata values |
opengraph-image file |
A static image should live beside its route | The file convention controls the route image and its precedence |
opengraph-image.tsx |
The image should be generated from route content | Generation and caching behavior depend on the route’s data needs |
Current Next.js documentation specifies an 8 MB maximum for an opengraph-image file and a 5 MB maximum for a twitter-image file. These are Next.js file convention constraints, not universal limits for every preview crawler. Check the current file convention documentation when choosing an asset.
5. Verify the HTML and image that crawlers receive
- Request the exact public URL you plan to share. Inspect the raw response HTML, not only the browser’s live Elements panel.
- Find the
og:imagetag and confirm there is one intended value for that route. Check the title, description, URL, and type while you are there. - Open the image URL independently. Confirm it resolves to the intended image and that the crawler can fetch it without a login, blocked request, or unsuitable redirect.
- Compare the route’s tags with parent and child metadata definitions. In Next.js, check whether a child
openGraphobject replaced fields inherited from its parent. - Use the destination platform’s preview or debugging tool to see what it fetched. If the HTML and image are correct but the displayed preview is old, a cached preview may be involved; cache behavior and debugging tools vary by platform.
One simple command-line inspection is to fetch the page HTML and search for the tag. This uses curl and assumes the response is text HTML.
curl -L -sS https://example.com/articles/example \
| grep -i 'property="og:image"'
If the command finds no tag, that is evidence that the returned HTML does not contain the expected literal markup. If the application injects metadata only after rendering in a browser, investigate server rendering or prerendering for that route. If the tag appears, copy its image URL and check that URL separately.
6. Troubleshoot missing, wrong, or stale previews
| Symptom | Likely cause | What to do |
|---|---|---|
| No image preview | The response HTML lacks og:image, or the crawler cannot fetch its URL |
Inspect raw HTML, then test the image URL and access rules |
| Browser shows the tag; shared link does not | The tag is added client-side after initial HTML is returned | Render or prerender route metadata into the response |
| Every route shows the same image | A default image is being used, or route data is not connected to metadata | Return metadata from the specific route record; inspect the raw response for each URL |
| Image is correct but title or description is missing | A child Next.js openGraph object replaced the parent object |
Include the shared fields in the child metadata intentionally |
| Preview still shows an old image | The platform may be using a cached preview | Use that platform’s preview/debugging tool to inspect its fetch; platform cache behavior varies |
| Image URL works in your browser only | Authentication, access rules, or redirects prevent crawler access | Make the intended asset publicly fetchable and inspect redirects and server rules |
| Next.js build rejects an image file | The file may exceed the documented convention limit or use an unsupported setup | Check the current image file reference and reduce or replace the asset as needed |
7. Keep route previews reliable as the app grows
Centralize how route data becomes metadata so titles, descriptions, page URLs, and image URLs do not drift apart. For dynamic content, handle missing records and missing share images explicitly. A fallback should be a known site-wide image, not a URL assembled from untrusted or incomplete data.
Test representative routes from the raw response after deployment, especially routes that use different layouts or image generation. Also check routes with unusual characters, redirects, and data that may not exist. A metadata implementation can be correct in development but differ after deployment if the production route, image host, or cache behavior differs.
For generated images, consider whether generation depends on request-time data or uncached data, since that affects static optimization according to Next.js documentation. Keep image assets within framework file limits, and ensure the image host can serve the file when a crawler requests it. The goal is a stable, publicly retrievable image URL and route-specific HTML.
8. Or skip the browser setup
If your goal is to inspect the page’s rendered appearance or produce a screenshot of a route while working on metadata, ScreenshotNeo is a website screenshot API and MCP server for developers. It is separate from setting the page’s Open Graph tags: the tags still need to be delivered in your site’s HTML. A single GET request captures a URL as an image or PDF. See the ScreenshotNeo website and API documentation.
curl -G "https://api.screenshotneo.com/v1/shot" \
-d access_key=YOUR_API_KEY \
--data-urlencode url=https://example.com/articles/example \
-o shot.webp
Python:
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={
"access_key": "YOUR_API_KEY",
"url": "https://example.com/articles/example",
},
timeout=90,
)
open("shot.webp", "wb").write(r.content)
Node.js:
const q = new URLSearchParams({
access_key: 'YOUR_API_KEY',
url: 'https://example.com/articles/example',
})
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`)
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`)
await Bun.write('shot.webp', res)
ScreenshotNeo accepts cookie and consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers identify the page verdict and billing status. Its MCP server offers take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000.
Sign up free for 1,000 screenshots a month, with no card required.
9. Frequently asked questions
Does an Open Graph image replace the page’s social metadata?
No. It identifies the image for the preview. Set the page title, description, URL, and type as appropriate alongside it.
Should I use a relative path for og:image?
Prefer an absolute URL. It makes the intended image location explicit to services fetching the shared page.
Can I use a different image on every React route?
Yes. Render or generate metadata from each route’s data, and verify the response for each public URL.
Will React Helmet or a similar client-side helper guarantee previews?
A helper can update the live document, but that does not guarantee every crawler sees the update. Verify the initial HTML or use server rendering or prerendering for dependable route metadata.
Which Next.js approach should I choose?
Use the metadata API when you want explicit or data-derived fields. Use the image file convention when a static or generated image naturally belongs to a route segment.


