LoginSignup
2
3

More than 1 year has passed since last update.

【Astro】OGP画像を設定する

Last updated at Posted at 2023-02-19

はじめに

Astroで作ったWebサイトにOGP画像を設定したときのメモです。
OGP画像は画像ソースのURLに相対パスではなく絶対パスを指定する必要があったので、少し調べて設定しました。

手順

OGP画像配置

public フォルダにogp.png を配置しました。(faviconと同じ場所)

URL作成

レイアウト用のファイルに追記します。
まずはOGP画像用のURLを作成します。

const canonicalURL = new URL(Astro.url.pathname, '本番環境のWebサイトURL');
const ogpImageURL = new URL('/ogp.png', canonicalURL);

これで、本番環境のWebサイトURL/ogp.png にアクセスすると、OGP画像が表示されるようになります。

余談

ちなみに、公式ドキュメント には新しいURLの作成についてのサンプルコードが載っています。

// Example: Construct a canonical URL using your production domain
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
// Example: Construct a URL for SEO meta tags using your current domain
const socialImageURL = new URL('/images/preview.png', Astro.url);

Astro.site はローカル環境でundefined になってしまいエラーになるので、イケてないですがサイトのURLをべた書きしました。
new URL('/images/preview.png', Astro.url) を使うと、本番環境でローカル環境のURLが生成されてしまったので使いませんでした。

headタグに追加

上と同じレイアウト用のファイルに追記します。

<!DOCTYPE html>
<html lang="ja">
    <head prefix="og: https://ogp.me/ns#">
        (略)
        <meta property="og:image" content={ogpImageURL} />
        (略)
    </head>
    <body>
        <slot />
    </body>
</html>
(略)

これでOGP画像を設定することができました!
設定確認は以下のサイトを使うと便利です。

参考文献

2
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3