Security, Tech & Programming
How to add custom inline javascript to NextJs

How to add custom inline javascript to NextJs

Use the following method to include the custom javascript code as inline javascript on your nextjs page:

NextJs add Script inline

// import next/script on top of the file
import Script from "next/script";

// add following code where you want javascript output to be added:
// node that id is required
<Script id="custom-id">
    {`
      console.log("ping - pong, working!");
    `}
</Script>

Replace the content inside {` ... `} with whatever you want to output.

How to add Facebook Pixel to nextjs page

To add facebook pixel, get your facebook pixel code and place it where you want to show this code in your files: (replace YOUR-FB-PIXEL-ID-HERE with your own here, or simply use the complete code from facebook)

<Script
  id="fb-pixel-1">
    {`
        !function(f,b,e,v,n,t,s)
        {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
        n.callMethod.apply(n,arguments):n.queue.push(arguments)};
        if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
        n.queue=[];t=b.createElement(e);t.async=!0;
        t.src=v;s=b.getElementsByTagName(e)[0];
        s.parentNode.insertBefore(t,s)}(window, document,'script',
        'https://connect.facebook.net/en_US/fbevents.js');
        fbq('init', 'YOUR-FB-PIXEL-ID-HERE');
        fbq('track', 'PageView');
    `}
</Script>

For more scenarios and details, see this link:

https://medium.com/frontendweb/the-script-component-in-next-js-ee6ee6cd705a

Leave a Reply

Your email address will not be published. Required fields are marked *

Hire Me!