Search code examples
typescriptnext.js

How to put a script in the head tag in next.js?


I'm using next.js with src/app directory structure and as far as I understand, this structure doesn't support using next/head, so I have a question, how can I put the script and other tags for certain pages in the <head></head> tag?


Solution

  • Inside the layout.tsx file at the root of the app folder you would typically add scripts there since you can have <head> tags inside.

    If you need to add them on specific pages, you can directly use the Script component.

    By default the Script component will use a afterInteractive strategy which would mean that you script would load after the page has been hydrated. In case you need the script to be in the head of the document you can always use beforeInteractive strategy which will always put the script on the head, no matter where in the component tree it will be located.