Next.js Discord

Discord Forum

How to add script to head tag?

Unanswered
Spectacled Caiman posted this in #help-forum
Open in Discord
Spectacled CaimanOP
I received data like image from backend, how to parse and add them to head tag and body tag

7 Replies

Mossyrose gall wasp
do you want to add gtm script?
gtm.ts
type WindowWithDataLayer = Window & {
  dataLayer: Record<string, any>[];
};

declare const window: WindowWithDataLayer;

export const GTM_ID = process.env.NEXT_PUBLIC_GTM;

export const pageview = (url: string) => {
  if (typeof window.dataLayer !== "undefined") {
    window.dataLayer.push({
      event: "pageview",
      page: url,
    });
  } else {
    console.log({
      event: "pageview",
      page: url,
    });
  }
};

analytics.tsx
"use client";

import { usePathname, useSearchParams } from "next/navigation";
import Script from "next/script";
import { useEffect } from "react";

import { GTM_ID, pageview } from "@/utils/lib/gtm";

const Analytics = () => {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    if (pathname) {
      pageview(pathname);
    }
  }, [pathname, searchParams]);

  if (process.env.NEXT_PUBLIC_VERCEL_ENV === "development") {
    return null;
  }

  return (
    <>
      <noscript>
        <iframe
          src={`https://www.googletagmanager.com/ns.html?id=YOUR_GTM_ID`}
          height="0"
          width="0"
          style={{ display: "none", visibility: "hidden" }}
        />
      </noscript>
      <Script
        id="gtm-script"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
    (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
    new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
    j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
    'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
    })(window,document,'script','dataLayer', 'YOUR_GTM_ID');
  `,
        }}
      />
    </>
  );
};
export default Analytics;

and import this inside root layout wrapped with Suspense
Spectacled CaimanOP
Thank you for your help, but what I mean is that those scripts are added by the administrator, and when I get that sequence, I have to add them to the head tag
Mossyrose gall wasp
fetch your script then use inside your script like below:
<script dangerouslySetInnerHTML={{ __html: YOUR_GTM_SCRIPT }} />
Spectacled CaimanOP
it warning like this
Mossyrose gall wasp
those script format not looks like true if you check my script you can see you should format it like mine
you can paste your header and body tags here?