Build such cool preview images!

February 14, 2022

Liked what you saw? This is how our link previews will look like, when you reach the end of this blog.

jsx-to-vdom

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.

"Talk is cheap. Show me the code" ~ Linus Torvalds

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 .

jsx-to-vdom

Add following code to your route.tsx

import { NextRequest } from "next/server";
 
export const runtime = "edge";
 
export async function GET(request: NextRequest) {
  return new Response("Hello, World!");
}

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

jsx-to-vdom

Step 2

Get search params from the browser.

export async function GET(request: NextRequest) {
  const { searchParams } = request.nextUrl;
 
  const hasTitle = searchParams.has("title");
 
  let title = hasTitle ? searchParams.get("title") : "Open Graph";
 
  return new Response(`Hello, ${title}!`);
}

Add above code and sprint towards your browser to check what you just did.

jsx-to-vdom

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

jsx-to-vdom

Use this image in your route.tsx, replace return new Response with new ImageResponse because we are using image as background here.

return new ImageResponse(
  (
    <div
      style={{
        height: "100%",
        width: "100%",
        position: "relative",
        color: "white",
        display: "flex",
        backgroundImage: `url(http://localhost:3000/_static/blog-og-card.png)`,
      }}
    >
      <div
        style={{
          width: 744,
          fontSize: 40,
          position: "absolute",
          left: 240,
          top: 150,
          color: "black",
        }}
      >
        {title}
      </div>
    </div>
  )
);

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.

jsx-to-vdom

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.

jsx-to-vdom

Add following code in your page.tsx

export async function generateMetadata({ params }: any) {
  // https://og-image-generation-olive.vercel.app
  // 👆 is the domain i got after deploying code to vercel more on this later.
  const ogImage = `https://og-image-generation-olive.vercel.app/og?title=${params.id}`;
 
  return {
    title: params.id,
    openGraph: {
      title: params.id,
      url: "./",
      images: [
        {
          url: ogImage,
          width: 1200,
          height: 630,
          alt: params.id,
        },
      ],
    },
  };
}
 
const BlogDetails = () => {
  return <div>Blog Details</div>;
};
 
export default BlogDetails;

Head over to browser you should see something like this

jsx-to-vdom

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