Liked what you saw? This is how our link previews will look like, when you reach the end of this blog.
Let's dive in! Next.js comes with two runtime Edge and Node.js where part of your application code can be rendered. For building dynamic link previews we'll use Edge runtime.
Alright let's build 🚀
For the scope of this blog i am assuming you have a Next.js app on your machine just lying around the corner.
We'll be using app
router for this tutorial because pages
are ancient history now and we don't talk about them here.
Step 1
Make a folder called og
inside your app directory with a file route.tsx
, og
here stands for "only gangster" :p, okay fine i am kidding for all you dorks out there og stand for Open Graph
.
Add following code to your route.tsx
Here we specify which runtime environment we are using to render our image.
Run to your browser you'll see something like this when you visit http://localhost:3000/og
Step 2
Get search params from the browser.
Add above code and sprint towards your browser to check what you just did.
Step 3
Okay now comes the fun part, spend atleast 5 hours to find THE perfect background image for your preview, once done add that public/_static/
folder
Use this image in your route.tsx
, replace return new Response
with new ImageResponse
because we are using image as background here.
But wait how did i generate this code? Magic? nope well you can see how your preview looks on Vercel Og Playground
Once done, march towards your browser to see the changes.
Step 4
If you made it till here, give yourself a pat on the back! We are almost done.
Aim is to add this og
link inside meta
, let's create a folder named blog
and [id]
with page.tsx
for route.
Add following code in your page.tsx
Head over to browser you should see something like this
Here we generate dynamic meta data, and pass params.id
which is nothing but our blogid
Once done, deploy your project to any hosting platform like vercel or netlify. Copy the domain name given by them, in my case vercel gave me https://og-image-generation-olive.vercel.app/
as the domain.
Now replace your http://localhost:3000
with domain name and push those changes again. And that's it you should now be able to generate dynamic images based on your query params on the fly!
Alright that's a wrap ✨
References:
Edge Runtime
Open Graph(OG) Image Generation
Vercel OG Image Playground
Generate Dynamic Meta Data
If you liked this blog or have any feedback or maybe just want to chill? feel free to reach out to me @Twitter, @Linkedin