Fix Next.js Open Graph Images Showing localhost URLs in Production
Published: May 6, 2025
The Issue
I deployed my Next.js app, shared a link on social media, and instead of showing your real domain, the Open Graph images still pointed to http://localhost:3000/...
.
Example of what you don’t want:
http://localhost:3000/services/{serviceName}/opengraph-image.jpg
What you expect:
https://yourdomain.com/services/{serviceName}/opengraph-image.jpg
This happens often when hosting on your own VPS (Digital Ocean, AWS, Hetzner, etc.) instead of Vercel.
Why It Happens
Next.js tries to guess your base URL when generating metadata.
- In dev, it defaults to
localhost:3000
. - On Vercel, it detects the domain automatically.
- On custom servers, it doesn’t always know your domain and falls back to
localhost
.
The Fix: metadataBase
You need to explicitly tell Next.js your site’s base URL.
Add metadataBase
in your root layout
// app/layout.tsx
import type { Metadata } from 'next';
export const metadata: Metadata = {
metadataBase: new URL('https://yourdomain.com')
// other metadata like title, description, etc.
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
BTW, i hope you do know you have to replace https://yourdomain.com
with your actual domain right…just saying.
You may want to make it dynamic
Use an environment variable so it works across dev and production:
// app/layout.tsx
export const metadata: Metadata = {
metadataBase: new URL(process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000')
};
Then set it on your server:
NEXT_PUBLIC_APP_URL=https://yourdomain.com
How It Works
Once metadataBase
is set, Next.js automatically converts relative metadata URLs into absolute ones.
Example:
export const metadata: Metadata = {
openGraph: {
images: ['/my-og-image.jpg'] // relative
}
};
Becomes:
https://yourdomain.com/my-og-image.jpg
Before vs After
Before (broken): http://localhost:3000/services/dstv/opengraph-image.jpg
After (fixed): https://yourdomain.com/services/dstv/opengraph-image.jpg
Let's connect
Always interested in good conversations about technology, football, or interesting projects.