strapi / nextjs-corporate-starter

Strapi Demo application for Corporate Websites using Next.js
MIT License
959 stars 285 forks source link

Opengraph image has incorrect URL when using dynamic route #79

Closed colonder closed 9 months ago

colonder commented 10 months ago

Summary

I'm trying to dynamically generate opengraph image, and I placed opengraph-image.tsx in /src/app/[lang] directory. I used the following code

import { ImageResponse } from "next/server";
import { getGlobal } from "./utils/get-globals";
import { getStrapiMedia } from "./utils/api-helpers";
import { Picture } from "./utils/models";

export const contentType = "image/png"

export default async function Image({ params }: { params: { lang: string } }) {
    const meta = await getGlobal(params.lang);
    const shareImage: Picture = meta.data.attributes.metadata.shareImage
    const imgUrl = getStrapiMedia(shareImage.data.attributes.url);

    return new ImageResponse(
        (
            <div tw="relative flex w-full h-full items-center justify-center">
                {/* Background */}
                <div tw="absolute flex inset-0">
                    <img
                        tw="flex flex-1"
                        src={imgUrl || ""}
                        alt={shareImage.data.attributes.alternativeText}
                    />
                </div>
            </div>
        ),
        {
            width: shareImage.data.attributes.width,
            height: shareImage.data.attributes.height
        }
    )
}

The meta tag is generated as

<meta property="og:image" content="http://localhost:3000/[lang]/opengraph-image/?c5620f0c68b1d1fa"/>

and the preview is not visible neither in the browser nor in messaging apps. When I type the above link in my browser as is, the image is not found, but when I replace the [lang] part with a specific language like en it works just fine. How can I fix it? Another question: can I make just one OG image for the entire app or do I have to create this file in every single directory with page.tsx?

PaulBratslavsky commented 10 months ago

@colonder I have found this article https://medium.com/@moh.mir36/open-graph-with-next-js-v13-app-directory-22c0049e2087 that walks through how to implement opengraph image in Next 13.

Let me know if that helps.

colonder commented 9 months ago

Yes, I must've understood smth wrong about how OG works.