Skip to main content
Dude LemonDude Lemon
ServicesWorkAboutBlogCareers
LoginLet's Talk
Home/Blog/How to Install a Tracking Code in Your Website Header and Body
Engineering

How to Install a Tracking Code in Your Website Header and Body

A clear, platform-by-platform guide to adding analytics and marketing tracking codes to the head and body of any website, with copy-ready snippets and a verification checklist.

DL
Shantanu Kumar
Chief Solutions Architect
June 14, 2026
18 min read
Updated June 2026
XinCopy

Almost every analytics tool, ad platform, and customer messaging product asks you to do the same thing before it can work: paste a small tracking code into your website. Google Analytics, Google Tag Manager, the Meta Pixel, LinkedIn Insight, and visibility tools like our own SearchLift all rely on this one step. Get it right and your data is accurate from day one. Get it wrong and you spend weeks wondering why your numbers look broken.

This guide explains exactly what a tracking code is, the difference between the head and body of your site, and how to install one on the platforms most businesses actually use: raw HTML, Wix, Shopify, WordPress, Squarespace, Webflow, Framer, and a custom React or Next.js app. Every snippet below is copy ready.

A tracking code only works if it loads on every page you want to measure. Sitewide placement is the whole job.

What a tracking code actually is

A tracking code, also called a tracking pixel, tag, or snippet, is a short piece of JavaScript that loads a remote script from a vendor. When a visitor opens your page, that script runs in their browser, records an event such as a page view, and sends it back to the vendor for reporting. It does not change how your page looks. It runs quietly in the background.

Most tracking codes look like this in their simplest form: a single async script tag pointing at the vendor. The example below is the exact format used by a modern visibility tool, and it is representative of what you will paste for most products.

htmlA typical async tracking snippet
1<script async src="https://example-vendor.com/a.js?k=YOUR_SITE_KEY"></script>

Head vs body: where tracking codes go and why

Every HTML page has two main containers. The head holds metadata and scripts that the browser reads before rendering the visible page. The body holds the content people actually see. Vendors tell you where to place their code because the location affects both accuracy and page speed.

  • Head: use this for analytics and tag managers that need to start measuring as early as possible, such as Google Analytics 4 and Google Tag Manager. Loading early means you do not miss fast bounces.
  • Body: some tools provide a second snippet that goes immediately after the opening body tag. Google Tag Manager is the most common example, where the body snippet is a no-JavaScript fallback.
  • End of body: heavier scripts that are not critical to first paint can load just before the closing body tag so they do not block your content from appearing.

Here is where each location lives in a standard HTML document. When a platform says paste in the head or paste after the opening body tag, these are the exact spots they mean.

htmlindex.html
1<!DOCTYPE html>
2<html lang="en">
3 <head>
4 <meta charset="utf-8" />
5 <title>Your Site</title>
6
7 <!-- HEAD: analytics and tag manager go here -->
8
9 </head>
10 <body>
11
12 <!-- BODY (top): tag manager no-script fallback goes here -->
13
14 <main>Your visible content</main>
15
16 <!-- BODY (bottom): heavy non-critical scripts can go here -->
17
18 </body>
19</html>
If a vendor gives you two snippets, they are not optional alternatives. Install both, in the order the vendor specifies.

The two codes you will install most often

Before the platform steps, here are the two most common tracking codes so you know what you are pasting. The first is Google Analytics 4, which is a single head snippet. The second is Google Tag Manager, which has a head snippet and a body snippet.

htmlGoogle Analytics 4 (head only)
1<!-- Google Analytics 4 -->
2<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
3<script>
4 window.dataLayer = window.dataLayer || [];
5 function gtag(){ dataLayer.push(arguments); }
6 gtag('js', new Date());
7 gtag('config', 'G-XXXXXXXXXX');
8</script>
htmlGoogle Tag Manager (head snippet)
1<!-- Google Tag Manager -->
2<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
3new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
4j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
5'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
6})(window,document,'script','dataLayer','GTM-XXXXXXX');</script>
7<!-- End Google Tag Manager -->
htmlGoogle Tag Manager (body snippet, right after the opening body tag)
1<!-- Google Tag Manager (noscript) -->
2<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX"
3height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
4<!-- End Google Tag Manager (noscript) -->

Replace G-XXXXXXXXXX and GTM-XXXXXXX with your own IDs from the vendor dashboard. Everything that follows is about where these snippets go on each platform.

Raw HTML or a hand-coded site

If you own the HTML files, this is the most direct method. Paste the head snippet just before the closing head tag, and any body snippet just after the opening body tag. If your site has many pages, put the code in a shared include or template so it loads everywhere automatically.

htmlPlacement in a static page
1<head>
2 <!-- ... your meta and styles ... -->
3
4 <!-- paste head tracking snippet here, last thing before </head> -->
5 <script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
6 <script>
7 window.dataLayer = window.dataLayer || [];
8 function gtag(){ dataLayer.push(arguments); }
9 gtag('js', new Date());
10 gtag('config', 'G-XXXXXXXXXX');
11 </script>
12</head>
13<body>
14 <!-- paste body tracking snippet here, first thing after <body> -->
15
16 <!-- rest of your page -->
17</body>

Wix

  • Open your Wix dashboard and go to Settings, then Custom Code under the Advanced section.
  • Click Add Custom Code at the top right.
  • Paste your snippet, give it a clear name, then choose where to apply it: All pages keeps tracking sitewide.
  • Under Place Code in, pick Head for analytics, or Body start for a tag manager body snippet.
  • Set Load code on pages to All pages and Load once, then click Apply.

Wix also has built-in fields for Google Analytics under Marketing and SEO, so for GA4 you can paste only the measurement ID instead of the full snippet. For anything else, the Custom Code panel is the reliable path.

Shopify

For sitewide scripts in Shopify, edit the theme layout file so the code loads on every storefront page. From your admin, go to Online Store, then Themes, open the three-dot menu and choose Edit code, then open layout/theme.liquid.

liquidlayout/theme.liquid
1<head>
2 {{ content_for_header }}
3
4 <!-- paste head tracking snippet here -->
5 <script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
6 <script>
7 window.dataLayer = window.dataLayer || [];
8 function gtag(){ dataLayer.push(arguments); }
9 gtag('js', new Date());
10 gtag('config', 'G-XXXXXXXXXX');
11 </script>
12</head>
13<body>
14 <!-- paste body tracking snippet here -->
15
16 {{ content_for_layout }}
17</body>

For Google Analytics specifically, Shopify also offers a managed setup through Settings, then Customer events, which avoids editing theme code. Checkout pages on Shopify can require this customer events route, so prefer it when you need conversion tracking through checkout.

WordPress

  • Easiest path: install a header and footer scripts plugin, then paste the head snippet into the header field and any body or footer snippet into the matching field. This survives theme updates.
  • Theme path: in Appearance, then Theme File Editor, add the head snippet to header.php just before the closing head tag. This can be overwritten when the theme updates, so a child theme or plugin is safer.
  • Block themes: use the Site Editor or a plugin, since classic header.php may not exist.

Squarespace

  • For sitewide code, go to Settings, then Developer Tools, then Code Injection.
  • Paste head snippets into the Header field and body snippets into the Footer field.
  • For a single page only, use Page Settings, then Advanced, then the page header code injection box.
  • Note that Code Injection requires a Business plan or higher on Squarespace.

Webflow

  • Sitewide: go to Project Settings, then Custom Code. Paste head snippets in Head Code and body snippets in Footer Code, then publish.
  • Single page: open Page Settings for that page and use the Before head tag or Before body tag fields.
  • Custom code in the head and footer only runs on the published site, not in the Designer preview, so always verify after publishing.

Framer

  • Open Project Settings, then the General tab, and find Custom Code.
  • Use Start of head tag for analytics and tag manager head snippets.
  • Use Start of body tag for tag manager body snippets.
  • Publish the site, since custom code does not execute in the editor.

React or Next.js custom app

On a custom build you control the document head directly. In the Next.js App Router, the cleanest place for a sitewide tracking code is the root layout, so it renders into every page. The example below mirrors how we install analytics across the sites we build.

jsxapp/layout.jsx
1export default function RootLayout({ children }) {
2 return (
3 <html lang="en">
4 <head>
5 {/* head tracking snippet */}
6 <script
7 async
8 src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"
9 />
10 <script
11 dangerouslySetInnerHTML={{
12 __html: `
13 window.dataLayer = window.dataLayer || [];
14 function gtag(){ dataLayer.push(arguments); }
15 gtag('js', new Date());
16 gtag('config', 'G-XXXXXXXXXX');
17 `,
18 }}
19 />
20 </head>
21 <body>{children}</body>
22 </html>
23 )
24}

For most vendor pixels a plain async script tag is enough, and you can drop it straight into the head as shown. If you need finer control over load timing, the Next.js Script component lets you set a strategy such as afterInteractive so the tag does not compete with your first paint.

How to verify the tracking code is working

Never assume installation worked. Confirm it in the browser before you trust any numbers. Three quick checks catch almost every mistake.

  • View source: open your live page, view the page source, and search for the vendor ID or script URL. If it is missing, the code did not save sitewide.
  • Network tab: open developer tools, go to the Network tab, reload, and filter by the vendor domain. You should see the script request return a 200 status.
  • Vendor real-time view: open the analytics dashboard real-time report, visit your own site, and confirm your session appears within a minute.
javascriptQuick console check for Google tags
1// Paste in the browser console on your live page.
2// Returns true if the Google tag global is present.
3typeof window.gtag === 'function' && Array.isArray(window.dataLayer);

“Tracking you have not verified is not data. It is a guess with a dashboard.”

Dude Lemon delivery guideline

Common mistakes to avoid

  • Installing on one page instead of sitewide, so most traffic is never counted.
  • Pasting the body snippet into the head, or skipping the body snippet entirely for Google Tag Manager.
  • Adding the same tag twice, once directly and once through a tag manager, which doubles your numbers.
  • Forgetting to publish on platforms like Webflow and Framer where custom code only runs on the live site.
  • Pasting a placeholder ID and never replacing it with your real measurement ID.

Once the basics are in place, a tag manager is the cleanest way to add, edit, and remove tags without touching site code again. If you would rather have analytics, conversion tracking, and consent handling designed correctly from the start, that is part of how we approach custom software and web engineering, and you can talk with our team to scope it.

Tracking is only the first half of the value. Once you can see what visitors do, the next step is acting on it: turning conversations into qualified leads with an AI customer inbox, and making sure search engines and AI assistants actually surface your business with AI search visibility. For more on putting analytics to work, see our guide to AI workflow automation for small businesses.

Adding marketing pixels: Meta, LinkedIn, and TikTok

Advertising pixels follow the same head-placement rule as analytics. They let an ad platform attribute conversions and build audiences. Each one is a head snippet that you paste sitewide, exactly like Google Analytics. The Meta Pixel, used for Facebook and Instagram ads, is the most common.

htmlMeta Pixel (head)
1<!-- Meta Pixel Code -->
2<script>
3 !function(f,b,e,v,n,t,s)
4 {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
5 n.callMethod.apply(n,arguments):n.queue.push(arguments)};
6 if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
7 n.queue=[];t=b.createElement(e);t.async=!0;
8 t.src=v;s=b.getElementsByTagName(e)[0];
9 s.parentNode.insertBefore(t,s)}(window, document,'script',
10 'https://connect.facebook.net/en_US/fbevents.js');
11 fbq('init', 'YOUR_PIXEL_ID');
12 fbq('track', 'PageView');
13</script>
14<noscript><img height="1" width="1" style="display:none"
15 src="https://www.facebook.com/tr?id=YOUR_PIXEL_ID&ev=PageView&noscript=1"/></noscript>
16<!-- End Meta Pixel Code -->

LinkedIn Insight Tag and the TikTok Pixel work the same way: copy the snippet from the ad platform, replace the ID, and paste it into the head sitewide. The strong recommendation once you have more than one of these is to stop pasting them individually and route everything through Google Tag Manager instead.

Why a tag manager beats pasting individual codes

If you install GA4, the Meta Pixel, LinkedIn, and a chat widget all by hand, every future change means editing site code again. A tag manager flips this around. You install one container snippet once, then add, edit, pause, and remove every other tag from a dashboard without touching the site.

  • One sitewide install instead of many separate edits.
  • Marketing can manage tags without a developer for each change.
  • Built-in preview and debug mode before anything goes live.
  • Version history, so a bad change can be rolled back instantly.
Install one tag manager container, then manage every other tag from a dashboard. It is the difference between a code change and a checkbox.

Performance: async, defer, and load order

Tracking codes should never make your site feel slow. The async attribute tells the browser to download the script without blocking the page, then run it when ready. Most vendor snippets already include async, which is why you see it in the examples above. Three rules keep tracking light.

  • Keep async on vendor scripts so they do not block first paint.
  • Do not stack a dozen pixels directly in the head. Route them through a tag manager that loads them in a controlled way.
  • On a custom app, use a load strategy such as afterInteractive so tags fire once the page is interactive, not before.
jsxNext.js Script component with a load strategy
1import Script from 'next/script'
2
3export default function Analytics() {
4 return (
5 <>
6 <Script
7 src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"
8 strategy="afterInteractive"
9 />
10 <Script id="ga4-init" strategy="afterInteractive">
11 {`
12 window.dataLayer = window.dataLayer || [];
13 function gtag(){ dataLayer.push(arguments); }
14 gtag('js', new Date());
15 gtag('config', 'G-XXXXXXXXXX');
16 `}
17 </Script>
18 </>
19 )
20}

Consent and privacy: when tracking must wait

In many regions, analytics and marketing tracking require visitor consent before they can run. The usual pattern is a consent banner that holds non-essential tags until the visitor agrees. Some teams choose to keep first-party analytics always on while gating advertising pixels. The right answer depends on your jurisdiction and legal advice, but the technical pattern is the same: load the tag only after the consent state allows it.

  • Essential tags that are required for the site to function can load immediately.
  • Analytics and advertising tags should respect the visitor consent choice where the law requires it.
  • A tag manager makes consent gating far easier, since it can trigger tags based on a consent variable instead of hard-coded script tags.

Whatever you decide, document it and make the banner honest about what runs. Consent handling is one of the details we build in deliberately, the same way we treat security and reliability across the systems we ship.

Troubleshooting: my tracking code is not working

When a tag refuses to report, the cause is almost always one of a short list. Work through them in order before contacting vendor support.

  • Not published: on Webflow, Framer, and similar builders, custom code only runs on the live site. Publish, then test.
  • Wrong scope: the code was added to one page instead of sitewide. Check that it loads on your home page and an interior page.
  • Wrong ID: a placeholder like G-XXXXXXXXXX or YOUR_PIXEL_ID was never replaced with the real value.
  • Blocked by an extension: ad and tracking blockers hide the request. Test in a clean browser profile with no extensions.
  • Caching: a CDN or page cache is serving the old version. Clear the cache and hard reload.
  • Duplicate tags: the same tag is installed twice, inflating numbers. Remove one source.
javascriptConfirm a specific vendor request fired
1// In the browser console on your live page, list scripts that
2// match a vendor. Adjust the match string to your vendor domain.
3performance.getEntriesByType('resource')
4 .filter((r) => r.name.includes('googletagmanager.com'))
5 .map((r) => r.name);

“Most broken tracking is not a vendor bug. It is a placement, a publish step, or a placeholder ID that never got replaced.”

Dude Lemon delivery guideline

Frequently asked questions

Does a tracking code slow down my website? Properly installed with the async attribute, the impact is minimal and not visible to users. Slowness usually comes from stacking many tags directly in the head, which a tag manager solves.

Can I put every tracking code in the head? Most analytics and pixels belong in the head. The main exception is a tag manager body snippet, which must go immediately after the opening body tag. Always follow the placement the vendor specifies.

Do I need a developer to install a tracking code? On hosted platforms like Wix, Shopify, Squarespace, and WordPress, no. Each has a built-in field for custom code. A developer helps when you have many tags, a custom app, or strict consent and performance requirements.

How do I know it is actually working? Use the three checks from earlier: search the page source for your ID, watch the Network tab for a 200 response, and confirm your visit in the vendor real-time report.

When to bring in help

A single analytics tag is a five-minute job you can do yourself with this guide. The work gets harder when you need accurate conversion tracking across a checkout, consent gating that satisfies your legal team, server-side tagging, or analytics wired into a custom application. That is engineering, not copy and paste.

If you want analytics, conversion tracking, and consent handled correctly from the start, that is part of how we build and operate custom software and web platforms. When you are ready to turn that visibility into outcomes, SearchLift helps search engines and AI assistants surface your business, and ConvertPilot turns the traffic you measure into qualified conversations. To talk through your setup, reach out to our team.

Need help building this?

Let our team build it for you.

Dude Lemon builds production-grade web apps, APIs, and cloud infrastructure. Get a free consultation and project proposal within 48 hours.

Start a Project
← PreviousHow ConvertPilot Unifies Chat, Email, WhatsApp, and Social Into One AI InboxAI Integration

In This Article

What a tracking code actually isHead vs body: where tracking codes go and whyThe two codes you will install most oftenRaw HTML or a hand-coded siteWixShopifyWordPressSquarespaceWebflowFramerReact or Next.js custom appHow to verify the tracking code is workingCommon mistakes to avoidAdding marketing pixels: Meta, LinkedIn, and TikTokWhy a tag manager beats pasting individual codesPerformance: async, defer, and load orderConsent and privacy: when tracking must waitTroubleshooting: my tracking code is not workingFrequently asked questionsWhen to bring in help
Need help building this?

Related articles

View all articles →
EngineeringWeb Application Development: A Complete Guide for Businesses in 2026Everything business leaders need to know about web application development - from architecture decisions and technology stacks to cost factors, timelines, and how to measure success.24 min readAI IntegrationHow ConvertPilot Unifies Chat, Email, WhatsApp, and Social Into One AI InboxA look at omnichannel AI customer support: how ConvertPilot brings every customer conversation into one inbox, drafts accurate replies, captures leads, and knows when to hand off to a human.9 min readSecuritySOC 2 Compliance Checklist for SaaS Startups: Complete 2026 Implementation GuidePractical SOC 2 compliance checklist for SaaS startups: scope, controls, evidence automation, audit execution, and sustainable operating cadence.36 min read
Dude LemonDude Lemon

Custom software development.
Built right. Shipped fast.

Start a project
Pages
HomeWorkConvertPilot AIGivePilotSearchLift AIAboutBlogCareers
Services
Wix DevelopmentShopify App DevelopmentAI DevelopmentMobile App DevelopmentCybersecurityCustom Portal DevelopmentAll Services
Connect
[email protected]Schedule Intro CallContact
© 2026 Dude Lemon LLC
TrustPrivacyTerms