Search code examples
facebook-graph-apinext.jsfacebook-opengraphserver-side-renderingvercel

Facebook fetching incorrect OG tags for NextJS project deployed on Vercel


I have built my project using NextJS and deployed it on Vercel. My project's Vercel URL is https://my-project.vercel.app. My domain (added to project settings in Vercel dashboard) is www.example.com

When I use Facebook Sharing Debugger to inspect the meta tags on a particular url, the meta tags are picked up correctly when using the my-project.vercel.app domain and not my actual domain www.example.com. The project loads correctly in the browser , including meta tags, for both domains.

For example, for a url /foo on my website, the og tags are picked up correctly for https://my-project.vercel.app/foo but not for https://www.example.com/foo.

Have a look at these screenshots. Note that the domain shown in the screenshots (esourcing.in) is added to the project esourcing-frontend.vercel.app, in the Vercel dashboard.

Screenshot 2020-10-24 at 4 14 48 PM

Screenshot 2020-10-24 at 4 16 24 PM

Here is the screenshot from my browser:

enter image description here


Solution

  • Answering my own question. There was a bug in my code

    The bug

    I am using a Wrapper component to wrap all my pages. I was setting the og_url after componentDidMount. I am using a functional component so the useEffect hook executes after component mount. Until that happens I set the og_url to https://example.com.

    However this component mounting never happens when the page is crawled by Facebook. So you can imagine that the og:url property was being set to https://example.com for all pages when the Facebook crawler scraped these pages.

    import Head from "next/head";
    import { useEffect } from 'react'
    
    const Wrapper = (props) => {
        const [og_url, setog_url] = useState("")
    
        useEffect(() => {
            setog_url(window.location.href)
        }, [])
    
        return (
            <>
                <Head>
                    ... other meta tags ...
    
                    <meta property="og:url" content={og_url ? og_url : "https://example.com"} />
    
                </Head>
                {props.children}
            </>
        )
    

    Fix

    og:url essentially tells Facebook that forget the OG tags on this page and use the OG tags from the page whose url is set to the value of og:url. I set the og:url to "" and now the sharing debugger picks up the right OG tags.