main image

Up Your Social Media Presence with Vercel's Auto-Generated OG Images

19 Oct 23 · views

Did you know that Vercel has its own Open Graph (OG) Image Generation feature? This is a great tool to enhance the engagement on your website.

This week, we will explore the process of integrating Vercel's auto-generated Open Graph (OG) images within a Next.js project.

An engaging preview image can generate more clicks when your site is shared. Let’s look into how Vercel's feature can boost your site’s social media presence.

Kickstarting Your Project

Begin by setting up a new Next.js project, if you don’t have one already.

npx create-next-app my-next-app
cd my-next-app

Next we want to install @vercel/og in order to make this work.

npm install @vercel/og next

Creating the Handler

Navigate to your project and create a new file, say og-image.tsx, under the pages/api directory. This is where our OG image generator will exist.

import { ImageResponse } from "@vercel/og";
import { NextRequest } from "next/server";

export const config = {
  runtime: "edge",
};

export default function handler(request: NextRequest) {
  // Our code will go here
}

Decoding The URL

Our endpoint will fetch the title and description from the URL. We'll slice these values to ensure they are of a reasonable length, providing defaults if they are absent.

const { searchParams } = new URL(request.url);

const title = searchParams.has("title")
  ? searchParams.get("title")?.slice(0, 100)
  : "Charles Krook";

const desc = searchParams.has("desc")
  ? searchParams.get("desc")?.slice(0, 100)
  : "Frontend Developer & Designer";

Crafting the image

Now it's time to craft the actual og image. We can do so with the ImageResponse we get from “@vercel/og”.

return new ImageResponse(
  (
    <div style={/* styles */}>
      <div style={/* styles */}>
        {/* Our content goes here */}
      </div>
    </div>
  ),
  {
    width: 1200,
    height: 630,
  }
);

Error Handling

Lets not forget to handle any errors that might occur during the process.

} catch (e: any) {
  console.log(`${e.message}`);
  return new Response(`Failed to generate the image`, {
    status: 500,
  });
}

Wrapping up

When you combine all these pieces, you should end up with a OG image generator that can take any title and description as parameter and generate its own image.

So for example, if you where to head over to this endpoint you should see the following og image:

Here is the final code that I'm using for my own website to auto generate the above OG image.

import { ImageResponse } from "@vercel/og";
import { NextRequest } from "next/server";

export const config = {
  runtime: "edge",
};

export default function handler(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);

    // ?title=<title>
    const hasTitle = searchParams.has("title");
    const hasDesc = searchParams.has("desc");

    const title = hasTitle
      ? searchParams.get("title")?.slice(0, 100)
      : "Charles Krook";

    const desc = hasDesc
      ? searchParams.get("desc")?.slice(0, 100)
      : "Frontend Developer & Designer";

    return new ImageResponse(
      (
        <div
          style={{
            backgroundColor: "#161515",
            backgroundSize: "150px 150px",
            height: "100%",
            width: "100%",
            padding: "4rem",
            display: "flex",
            flexDirection: "column",
            flexWrap: "nowrap",
            justifyContent: "center",
          }}
        >
          <div
            //This div
            style={{
              display: "flex",
              flexDirection: "column",
              justifyContent: "space-around",
            }}
          >
            <img
              alt="Vercel"
              height={100}
              src="http://localhost:3000/images/avatar.png"
              style={{ borderRadius: "2rem" }}
              width={100}
            />
            <h1
              style={{
                fontFamily: "Inter, sans-serif",
                fontSize: 64,
                fontStyle: "normal",
                letterSpacing: "-0.025em",
                fontWeight: "900",
                color: "white",
                marginBottom: "1rem",
                lineHeight: 1,
                whiteSpace: "pre-wrap",
              }}
            >
              {title}
            </h1>
            <p
              style={{
                color: "lightgray",
                fontSize: 32,
              }}
            >
              {desc}
            </p>
            <span style={{ color: "#494949", fontSize: 32 }}>
              charleskrook.com
            </span>
          </div>
        </div>
      ),
      {
        width: 1200,
        height: 630,
      }
    );
  } catch (e: any) {
    console.log(`${e.message}`);
    return new Response(`Failed to generate the image`, {
      status: 500,
    });
  }
}

Subscribe to my Newsletter!

Where I write about frontend development topics

Charles is a Stockholms based frontend developer and designer who specializes in creating captivating digital experiences. His acute sense of aesthetics and coding expertise allow him to seamlessly fuse creativity with functionality, turning concepts into visually stunning websites and apps.

Contact

hey@charleskrook.com
+46 70 023 05 43

Location

Stockholm
Sweden
© Charles Krook 2023 All rights reserved