What About Coding
By himanshu123Analyticsanalytcisgoogle search consolega4sitemaprobots

How to Set Up Google Search Console and Google Analytics (GA4) in a Next.js Website

Getting your Next.js site indexed and tracked correctly requires two tools: Google Search Console (for indexing and search performance) and Google Analytics 4 (for traffic and behavior data). This guide walks through both setups, step by step.

Prerequisites

  • A deployed Next.js website with a live domain (Vercel, Netlify, etc.)
  • Access to your codebase and ability to deploy changes
  • A Google account
  • Next.js 13.3+ if using App Router features like sitemap.ts and robots.ts

Part 1: Google Search Console Setup

1. Creating a Search Console Property

  1. Go to search.google.com/search-console
  2. Click Add Property
  3. Choose a property type: URL prefix — verifies one exact URL (e.g. https://yoursite.com). Simpler, faster.Domain — verifies all subdomains and protocols at once, but requires DNS access.

For most single-domain Next.js sites, URL prefix is the easier choice.

2. Verifying Website Ownership

Google offers several verification methods:

MethodBest for
HTML tagNext.js apps (recommended)
HTML file uploadStatic hosting with file access
DNS recordDomain property type
Google AnalyticsIf GA is already installed
Google Tag ManagerIf GTM is already installed

Recommended: HTML tag method.

Copy the meta tag Google provides, then add it to your metadata:

App Router (app/layout.tsx):

export const metadata = {
  verification: {
    google: "your-verification-code",
  },
};

Pages Router (pages/_document.tsx or _app.tsx):

<Head>
  <meta name="google-site-verification" content="your-verification-code" />
</Head>

Deploy your site, then click Verify in Search Console.

3. Submitting sitemap.xml

App Router — generate dynamically with app/sitemap.ts:

import type { MetadataRoute } from 'next'

export default function sitemap(): MetadataRoute.Sitemap {
  return [
    { url: 'https://yoursite.com', lastModified: new Date(), priority: 1 },
    { url: 'https://yoursite.com/about', lastModified: new Date(), priority: 0.8 },
  ]
}

Pages Router — place a static file at public/sitemap.xml, or generate one at build time with a script.

Then in Search Console: Sitemaps → enter sitemap.xml → Submit.

4. Submitting robots.txt

App Router — use app/robots.ts:

import type { MetadataRoute } from 'next'

export default function robots(): MetadataRoute.Robots {
  return {
    rules: { userAgent: '*', allow: '/', disallow: ['/login', '/dashboard'] },
    sitemap: 'https://yoursite.com/sitemap.xml',
  }
}

Pages Router — place robots.txt in the public/ folder:

User-agent: *
Allow: /
Disallow: /login
Disallow: /dashboard

Sitemap: https://yoursite.com/sitemap.xml

Google discovers robots.txt automatically once it's live — no manual submission needed, but you can verify it via Search Console's URL Inspection tool.

5. Requesting Indexing

For important pages you want indexed immediately:

  1. In Search Console, use the URL Inspection tool (top search bar)
  2. Paste the full page URL
  3. Click Request Indexing

Useful for new pages or after major content updates — don't overuse it, as it's rate-limited.


Part 2: Google Analytics (GA4) Setup

6. Creating a GA4 Property

  1. Go to analytics.google.com
  2. Click Admin → Create Property
  3. Enter your site name, timezone, and currency
  4. Choose Web as the platform when prompted for a data stream

7. Getting the Measurement ID

After creating the Web data stream, Google shows a Measurement ID (format: G-XXXXXXXXXX). Copy it — this is what connects your site to GA4.

8. Installing GA4 in Next.js

Use Next.js's official @next/third-parties package for optimized script loading:

npm install @next/third-parties@latest next@latest

Add the ID to .env.local:

NEXT_PUBLIC_GA_ID=G-XXXXXXXXXX

App Router (app/layout.tsx):

import { GoogleAnalytics } from '@next/third-parties/google'

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <GoogleAnalytics gaId={process.env.NEXT_PUBLIC_GA_ID!} />
      </body>
    </html>
  )
}

Pages Router (pages/_app.tsx):

import Script from 'next/script'

export default function App({ Component, pageProps }) {
  return (
    <>
      <Script
        strategy="afterInteractive"
        src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_ID}`}
      />
      <Script id="ga-init" strategy="afterInteractive">
        {`
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());
          gtag('config', '${process.env.NEXT_PUBLIC_GA_ID}');
        `}
      </Script>
      <Component {...pageProps} />
    </>
  )
}

9. Tracking Page Views

  • App Router: @next/third-parties automatically tracks page views on route changes — no extra code needed.
  • Pages Router: manually listen for route changes and send a pageview event:
useEffect(() => {
  const handleRouteChange = (url: string) => {
    window.gtag('config', process.env.NEXT_PUBLIC_GA_ID!, { page_path: url })
  }
  router.events.on('routeChangeComplete', handleRouteChange)
  return () => router.events.off('routeChangeComplete', handleRouteChange)
}, [router.events])

10. Verifying Analytics Is Working

  • Realtime report: In GA4, go to Reports → Realtime. Visit your live site in another tab — you should appear as an active user within 1–2 minutes.
  • Tag Assistant: Install the Google Tag Assistant Companion extension, open your site, and confirm the GA4 tag fires correctly with no errors.

Bonus: Adding Vercel Analytics

If your site is deployed on Vercel, you can add Vercel Analytics alongside GA4 for a lightweight, privacy-friendly view of traffic — no cookies, no env vars needed.

1. Install the package

bash

npm install @vercel/analytics

2. Add the component

App Router (app/layout.tsx):

tsx

import { Analytics } from '@vercel/analytics/next'

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <Analytics />
      </body>
    </html>
  )
}

Pages Router (pages/_app.tsx):

tsx

import { Analytics } from '@vercel/analytics/react'

export default function App({ Component, pageProps }) {
  return (
    <>
      <Component {...pageProps} />
      <Analytics />
    </>
  )
}

3. Enable it on Vercel

Go to your project on the Vercel dashboard → Analytics tab → click Enable. Redeploy your site if it wasn't already deployed after adding the component.

4. Verify it's working

Visit your live site, then check the Analytics tab in your Vercel dashboard — page views should appear within a few minutes (note: unlike GA4, there's no instant "Realtime" view; data can take a short while to populate).

Note: Vercel Analytics is a paid feature beyond the free tier's limited events/month — check current pricing on Vercel before relying on it for a high-traffic site. It complements GA4 rather than replacing it: GA4 gives deep behavioral/demographic data, while Vercel Analytics gives fast, zero-config performance-friendly pageview stats tied directly to your deployment.

How It Compares

Search ConsoleGA4Vercel Analytics
PurposeIndexing & search performanceDeep traffic/behavior dataSimple pageview/performance stats
Setup effortVerify ownership + submit sitemapInstall SDK + env var + Measurement IDInstall SDK, no env var
Data locationsearch.google.com/search-consoleanalytics.google.comVercel dashboard
Config neededMeta tag or DNS recordNEXT_PUBLIC_GA_ID env varNone — auto-configured

Common Mistakes & Troubleshooting

  • Verification fails: Meta tag wasn't deployed live before clicking Verify — always deploy first.
  • GA shows no data: Env var missing NEXT_PUBLIC_ prefix, so it's undefined in the browser.
  • Ad blockers: Realtime report shows 0 users — test in incognito with no ad blocker.
  • Sitemap/robots mismatch: Don't list blocked pages (e.g. /dashboard) in sitemap.xml.
  • Env vars not set on host: .env.local isn't deployed — add the same variable in your hosting provider's dashboard (e.g. Vercel → Project Settings → Environment Variables).
  • Duplicate GA tags: Don't combine @next/third-parties with a manually added gtag.js script — pick one method.

Share

More recent posts

View all