简体   繁体   中英

og image meta tag with Next.js is not working

<meta property="og:image" content="https://mywebsite.com/images/s1.jpg" 

I used next/head and I added the above meta tag image but when I shared the link the image didn't appear. how can I fix it?

For me it finally worked: Inside _app.js

import Head from "next/head"

then within the return:

<Head>
<meta property="og:image" content="https://myurl.com/ogImage.png" />
</Head>

then i did a static export and uploaded the files from the "out" folder via FTP, because i host the project on a non node server. to do this, open "package.json" and change "export" to "next build && next export". then just run npm run export in the console and the files will be exported to html

You can use this meta tag in the <head> tag

<meta property="og:image" content="https://mywebsite.com/images/s1.jpg"/>

<meta property="og:title" content="Your Title"/>

<meta property="og:description" content="A full description of the page."/>

<meta property="og:image:width" content="1200"/>

<meta property="og:image:height" content="630"/>

Please close properly meta tag you missed "/>" from your tag.

As it is said in the Next documentation :

Note: Only assets that are in the public directory at build time will be served by Next.js. Files added at runtime won't be available. We recommend using a third party service like AWS S3 for persistent file storage.

Thus, Next considers <meta> tags as a dynamic content, and doesn't do any build-time transformations, which leads to images not being used.

To fix that, you could either upload your image to some image hosting (or even to your own website), get this link and put it into og:image , or you could add a custom webpack loader to handle the image imports, like this :

import imageUrl from './logo.png';
import websiteUrl from './constants';

// somewhere in the head component
<meta property="og:image" content={`${websiteUrl}${imageUrl}`} />

Here, websiteUrl points to the hostname of your production website, eg https://example.com .

The last, and a crunchy option, is to add <img src="/logo.jpg" alt="" style={{ display: 'none'}} /> . This ensures that Next will process your image at build time, and you could add <meta property="og:image" content={websiteUrl + '/logo.jpg'} /> into the head. Good thing is that browsers don't initially load images with display set to none .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM