Next.js Discord

Discord Forum

custom script tag for home page alone

Unanswered
Egyptian Mau posted this in #help-forum
Open in Discord
Egyptian MauOP
Hello,

I am currently using Nextjs v14 App Router, and I want to add custom script script:ld+json in the <Head> tag of the Home Page alone not to any others pages, how I can achieve the same?

https://nextjs.org/docs/app/building-your-application/optimizing/metadata#json-ld

I've checked this Code, but this adds in the body of the HTML, not into the HEAD , can any one help me how to add this it in HEAD instead of BODY and that too only for Index/Home Page?

14 Replies

Egyptian MauOP
any help?
Egyptian MauOP
?
Egyptian MauOP
any help?
Egyptian MauOP
any help?
Egyptian MauOP
any help on this?
Create a layout.tsx in the same level as your page.tsx

Then define the return in layout.tsx as

return (
<html lang="en" className="">
<head>
YOUR SCRIPT HERE
</head>
<body className={${inter.className}}>
{children}
</body>
</html>
);
if hes talking about actually making the head only apply if the route is '/' you would need to have some logic in the layout that gets the path and applies the header based on that.
import { usePathname } from 'next/navigation'

const pathName = usePathname();

return (
    <html lang="en" className="">
      <head>
         {pathname == '/' ? script : null}
      </head>
      <body className={${inter.className}}>
        {children}
      </body>
    </html>
  );


Ive not tested this but sounds like it would work?
Make a client component and import into your layout in the head node?
Layout can’t be marked as use client but the layout will still accept an imported client component.
@Jboncz Layout can’t be marked as use client but the layout will still accept an imported client component.
Egyptian MauOP
if we need to use usePathname then it needs to be use client, right
Yes
I believe so. Just try it and you will have your answer 😬