How do you reference an absolute URL in Next.js <Head>?

163 Views Asked by At

I am trying to use next/head to dynamically set an og:image, which requires an absolute URL.

<meta property="og:image" content="https://example.com/og.jpg" />

How can I get https://example.com (the protocol and host)?

I tried using window.location.origin:

import Head from 'next/head';

const CustomHead = () => {
  const origin = typeof window !== 'undefined' ? window?.location?.origin : '';

  return (
    <Head>
      <meta property="og:image" content={`${origin}/og.jpg`} />
    </Head>
  );
}

But this always uses the '' fallback and renders /og.jpg, a relative URL, which is strange, because if I console.log(origin); I can see the absolute URL. What is happening here? Is it because <Head> is only being rendered once on the server?

Is there an environment variable that can be used to reference the absolute URL?

0

There are 0 best solutions below