Dev.to WebDev πŸ›  Dev πŸ‘ 2 πŸ“– 8 min read

Why my Next.js blog posts weren't getting indexed

For months, every article on my blog shipped with a line of HTML asking Google to ignore it and index my home page instead, and I was the one who wrote that line, in a layout file, without noticing anything wrong on the

For months, every article on my blog shipped with a line of HTML asking Google to ignore it and index my home page instead, and I was the one who wrote that line, in a layout file, without noticing anything wrong on the site while it was there.

In this post I want to walk you through how I found it, why Next.js was doing exactly what I had told it to do, the second trap I found hiding behind the same rule, and a quick check you can run on your own site in about a minute.

The symptom

My portfolio runs on Next.js 16 with the App Router, in Spanish and English, and the blog posts live in Supabase. Google Search Console kept listing my posts as "Crawled, currently not indexed," which meant Google had visited them and decided not to keep them, even though the pages themselves gave me no reason to worry. They loaded fast, the titles and descriptions were right and the social previews looked the way I expected.

Search Console doesn't tell you why it skips a page, so I opened the raw HTML of one post and searched for rel="canonical", and there was my home page where the post's own address should have been. I checked a second post and then a third, and every one of them pointed to the same place.

A canonical tag tells search engines which URL is the main version of a page when several URLs show similar content. Every post on my blog was effectively saying "the main version of me is the home page," so from Google's side each article looked like a copy of a page it already had. I can't prove that this tag was the only reason my posts weren't being indexed, but it was the one thing every affected page had in common, and it was actively telling Google to look somewhere else.

Where the tag came from

The tag came from the layout that wraps every page under each language.

// app/[locale]/layout.tsx, before (simplified)
export async function generateMetadata({ params }) {
  const { locale } = await params
  return {
    alternates: {
      canonical: `https://carlosjcastrog.com/${locale}`,
    },
    openGraph: {
      url: `https://carlosjcastrog.com/${locale}`,
    },
  }
}

When I wrote that code, the layout felt like the natural home for anything shared across the site, and since the home page needed a canonical, putting it there seemed like the tidy thing to do.

What I hadn't thought through is how Next.js builds the final metadata of a route. It evaluates every segment in order, from the root layout down to the page, and merges the results shallowly, so a key defined lower in the tree replaces the same key from above, while a key the page never defines is simply inherited from the closest segment that does. My blog post pages defined a title and a description but never touched alternates, so each one quietly inherited the canonical of the home page.

The Next.js documentation explains this merging behavior in its generateMetadata reference, and it shows alternates in examples for both layouts and pages, so the framework was never hiding anything from me. It also has no reason to warn you that a canonical in a layout becomes the canonical of every page below it, because it's doing exactly what it promises, and that is what makes this kind of bug so quiet. There's no build error, no console warning and nothing visible in the browser, and the only reader who ever notices is a crawler.

The same rule cuts the other way

While I was fixing it, I found the opposite problem waiting in the same code. Shallow merging also means that a page which defines a nested object replaces the whole object from the layout, not just the keys it mentions.

After the fix, my layout keeps only what I believed every page shared, which is the language for Open Graph.

// app/[locale]/layout.tsx, after
export async function generateMetadata({ params }) {
  const { locale } = await params
  if (!isLocale(locale)) notFound()
  const isEs = locale === "es"

  return {
    openGraph: {
      locale: isEs ? "es_AR" : "en_US",
      alternateLocale: isEs ? "en_US" : "es_AR",
    },
  }
}

That openGraph only reaches pages that don't define their own openGraph at all. My blog posts do define one, with the article type, URL, images and dates, so the layout's locale never makes it to them, and if I had trusted the layout to handle it, every shared post would have lost its language tags without a single error. Each post now sets locale and alternateLocale itself, and the layout value stays as a fallback for the simpler pages that don't define anything.

Seeing both problems side by side is what finally made the rule click for me. When a page leaves a key out, it inherits whatever the layout says, even when that value is wrong for it, and when a page defines a nested key, it loses everything the layout put inside it, including the parts you expected to keep. For values that really are shared, the docs suggest moving them into a variable and spreading them into each page, which turns accidental sharing into something you can see in the code.

The fix, one post at a time

Each post now builds its own canonical and its own language alternates. My articles exist in both languages under different slugs, so I couldn't build the other language's URL just by swapping the locale in the path. To solve that, each post in Supabase stores the slug of its translation in a linked_slug column, which lets the hreflang links point to the right article instead of a guessed URL that might not exist.

// app/[locale]/blog/[slug]/page.tsx (simplified)
const SITE = "https://carlosjcastrog.com"
const HREFLANG = { es: "es-AR", en: "en-US" } as const

export async function generateMetadata({ params }) {
  const { locale, slug } = await params
  const post = await getPostBySlug(slug, locale)
  if (!post) notFound()

  const url = `${SITE}/${locale}/blog/${post.slug}`
  const languages: Record<string, string> = { [HREFLANG[locale]]: url }

  if (post.linked_slug) {
    const other = locale === "es" ? "en" : "es"
    languages[HREFLANG[other]] = `${SITE}/${other}/blog/${post.linked_slug}`
  }

  return {
    title: post.title,
    description: post.excerpt,
    alternates: { canonical: url, languages },
    openGraph: {
      type: "article",
      url,
      locale: locale === "es" ? "es_AR" : "en_US",
      alternateLocale: locale === "es" ? "en_US" : "es_AR",
      publishedTime: post.published_at,
    },
  }
}

A few details in that code came from mistakes I'd rather you didn't repeat.

The canonical always points to the post in its own language, because Google recommends keeping a page's canonical in the same language, so the Spanish post is canonical for itself, the English post is canonical for itself and hreflang is what connects them. Pointing both versions at one of them would be asking Google to drop the other.

The two versions also link to each other in both directions, with the Spanish post listing the English one and the English post listing the Spanish one, since hreflang annotations that only go one way can be ignored.

Every URL is absolute, which is what Google recommends for canonical links, and Next.js would fail the build on a relative one anyway unless metadataBase is set.

Finally, getPostBySlug is wrapped in React's cache, because the same post is read once for the metadata and once for the page. Next.js automatically memoizes fetch calls between generateMetadata and the page, but my posts come from the Supabase client rather than fetch, so without cache every visit would have queried the database twice.

Validating the locale before building any URL

The layout used to read params.locale as if it would always be es or en, even though it's just a string that comes from the URL and anyone can type something else. A small guard now narrows it before anything uses it.

function isLocale(value: string): value is Locale {
  return (locales as readonly string[]).includes(value)
}

Unknown locales now return a 404 from both generateMetadata and the layout, instead of rendering a page whose canonical and hreflang would be built from a language the site doesn't have. This started as a TypeScript fix, and only later did I realize it was protecting the same URLs this whole post is about.

A function that had been doing nothing

In the same file, I found code that pinged Google with my sitemap every time I published a post. Google announced in June 2023 that the sitemap ping endpoint was going away and that requests would start returning 404 by the end of that year, which means my function had been sending requests into nothing for a long time without ever throwing an error, and I only noticed when I read the file again and removed it as part of the same change.

Today, the way to tell Google about your pages is a sitemap submitted in Search Console or listed in robots.txt, with an accurate lastmod for pages whose main content changed, and for a page that really matters, you can also request indexing from URL Inspection.

Check your own site in one minute

You don't need Search Console to find this bug, since a terminal is enough. Pick three pages that should have different canonicals, such as the home page, a listing and a single article, and compare what each one declares.

for path in / /en/blog /en/blog/some-post; do
  echo "$path"
  curl -s "https://example.com$path" \
    | sed -n '/<head/,/<\/head>/p' \
    | grep -o '<link rel="canonical"[^>]*>'
done

If two different pages print the same URL, a layout is probably handing its canonical down to pages that never asked for it. The script only reads inside <head> on purpose, because Google only accepts a canonical link that appears there, so if a page prints nothing, look for the tag elsewhere in the HTML before assuming it's missing.

For a second check, open URL Inspection in Search Console for one of your articles. It shows the canonical your page declares next to the one Google selected, and when those two disagree, Google is telling you it doesn't believe your page.

Where it stands

I deployed the fix, resubmitted the sitemap and requested indexing for my most important posts on November 29. It's still too early to show results, because Search Console can take weeks to recrawl pages and update its reports, so for now I'm watching the trend rather than any single day.

The biggest change is in how I think about layouts. I now treat anything in a layout's metadata as a value that every page below it will receive whether it wants it or not, and before I put a field there, I ask myself whether it's true for every single one of those pages. Most of the time the honest answer is no, and the field belongs in the page.

Have you ever found a bug that only a crawler could see?

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.