Simple Static Open Graph Image in Next.js App Directory On Vercel
I wanted a simple static open graph image for my Next.js app, built with the app directory architecture and hosted in Vercel. Why was this such a struggle? I don’t know, but the docs weren’t clear, and the top-rated solutions I found did not work. After some struggling, I found a simple working solution.
Open Graph Image File Conventions
The Next.js App Router introduces a new file convention to easily add opengraph-image and twitter-image properties to your pages. Add a specially named image file to a route and it will become the open graph image for that route. Read the full docs here: Open Graph File Convention.
Create a file named opengraph-image.(png|jpg|jpeg|gif) and place it in whatever route you want. If you want a specific Twitter (X) image, you use the syntax twitter-image.(jpg|jpeg|png|gif). See my example usage in the image below. I put mine in the highest route of my app so it would be automatically used for all children routes.
Create opengraph-image.alt.txt and twitter-image.alt.txt to provide helpful alt text for your og:image tag.
During the build step of your application, Vercel will generate the proper output based on your image.
This was the simplest working solution I could find, to get a static og:image working with Next.js App Directory and Vercel. Put the image you want in the route you want. For the initial release of my app I put the image in my top level route so all child routes would use the same image as well.
Vercel offers more advanced tools like the vercel/og package. But long pages of documentation shouldn’t be required to get a simple image to show up when I share my website.
💡 The above method did not work for me in Netlify as of August 2023. I did not get errors in my build, just no og:image in my final app. Using the Export Metadata object linked below did work for me in Netlify.
Previous Failed Attempts to get og:image to work
Adding meta property="og:image" directly in my app in the <Head> tag didn’t work