how to avoid the nextjs canonical trap - By Sourav Mishra (@souravvmishra)

why your next.js site might be getting de-indexed and how to fix it.

BySourav Mishra2 min read

you did everything right. you got your sitemaps and images, but google is still complaining about "duplicate canonicals".

welcome to the canonical trap lol.

i'm going to show you why next.js does this and how we fix it for clients.

the trailing slash problem

next.js thinks /blog and /blog/ are the same page. same for /blog?sort=new.

if you don't tell google which one is the main one, it gets super confused and might just ignore your page.


the fix: just tell it exactly

in next.js, you should always define the base url in your root layout.

// app/layout.tsx
import type { Metadata } from 'next';

export const metadata: Metadata = {
  metadataBase: new URL('https://souravvmishra.site'),
  title: 'my app',
  alternates: {
    canonical: './', 
  },
};

using ./ is a magic trick that tells next.js to use the current path and strip out all those messy query parameters.


dynamic pages

for stuff like blog posts, make the canonical match the slug exactly.

// app/blog/[slug]/page.tsx
export async function generateMetadata({ params }): Promise<Metadata> {
  const { slug } = params;
  
  return {
    title: `my post: ${slug}`,
    alternates: {
      canonical: `/blog/${slug}`, 
    },
  };
}

multiple languages

this is where it gets spicy. if you have /en/about and /fr/about, you need hreflang tags.

// app/[lang]/layout.tsx
export async function generateMetadata({ params }) {
  return {
    alternates: {
      canonical: `./`,
      languages: {
        'en-US': '/en',
        'fr-FR': '/fr',
      },
    },
  };
}

we literally saw a client lose 30% of their traffic because they forgot this step. google needs to know they are the same page but in different languages.


what to remember

  1. set metadataBase: if you don't, your links might break.
  2. use alternates.canonical: just do it everywhere.
  3. check search console: see what google actually thinks your canonical is.

if your site is still slow, read my production css guide.


written by sourav mishra, just trying to keep google happy.

Share this post

Cover image for how to avoid the nextjs canonical trap

You might also like

See all