Integrating ShareThis with Next.js

228 Views Asked by At

Has anyone tried to integrate ShareThis with Next.js?

I'm getting "Hydration failed because the initial UI does not match what was rendered on the server." and this, I have ascertained, is down to the inclusion of the ShareThis script tag.

I'm not sure what I need to do in order to resolve this error.

This is my _document.tsx file, containing the offending script tag:

import { Html, Head, Main, NextScript } from "next/document";

const Document = () => (
  <Html>
    <Head>

      <script
        type="text/javascript"
        src={`https://platform-api.sharethis.com/js/sharethis.js#property=${process.env.NEXT_PUBLIC_SHARETHIS_PROPERTY_ID}&product=sop`}
        async
        defer
      ></script>
    </Head>

    <body>
      <Main />

      <NextScript />
    </body>
  </Html>
);

export default Document;

Of course, the NEXT_PUBLIC_SHARETHIS_PROPERTY_ID variable from my .env file is being correctly populated.

1

There are 1 best solutions below

0
Adrian Teh On

You should be using next/script to load 3rd party scripts like ShareThis. Here's their documentation https://nextjs.org/docs/basic-features/script

Make sure to apply the <Script src="" /> component OUTSIDE of the next/head component, either above of below it.

Hope this helps.