casper's Profile Image

Full Stack Web/Mobile Developer

Nov, 2, 2024

How To Solve Next Js Opengraph Webp Image Format Problem

You can convert your webp format images to base64 image string to solve opengraph webp image format problem.

How To Solve Next Js Opengraph Webp Image Format Problem Image

Hi, If you have a problem like I had about generating dynamic opengraph images using .webp image format, this post will help you to fix it.

You need to create an api route to convert .webp format image to base64 string format.

Here is the api route:

// /app/api/getImageBase64/route.ts
import axios from "axios";
import { NextRequest } from "next/server";
import sharp from "sharp";

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;
  const url = searchParams.get("url");

  if (!url) {
    throw new Error("URL not found!");
  }

  const image = await axios
    .get<ArrayBuffer>(url, {
      responseType: "arraybuffer",
    })
    .then(async (res) => {
      const buffer = await sharp(res.data).toFormat("png").toBuffer();
      return {
        url: `data:${"image/png"};base64,${buffer.toString("base64")}`,
      };
    });

  return Response.json({ image });
}

opengraph-image.tsx:

import axios from "axios";

export const size = {
  width: 900,
  height: 450,
};

export const contentType = "image/png";

export default async function og() {
  // Query your post
  const post = {
    id: "123",
    image: "https://domain.com/image.webp"
  }

  let image;

    await axios
      .get(`${process.env.NEXT_PUBLIC_SITE_URL}/api/getImageBase64`, {
        params: {
          url: post.image,
        },
      })
      .then((res) => {
        image = res.data.image.url;
      });
  

  // You can return your ImageResponse however you want.
}
0
0

Comments (0)