How to add canonical meta tag in NextJs

Published on May 09, 2023

It’s important to add a canonical meta tag to your pages to improve SEO or to avoid issues with query params in crawled pages.

You can easily add a canonical meta tag in NextJs by using the next/head component.

import { useRouter } from 'next/router.js'
import Head from 'next/head.js'
// you need to access the route
const router = useRouter()

// then extract the path without template values (e.g. [...slug]) or query params
const canonicalUrl = (
  `https://usemiller.dev` + (router.asPath === '/' ? '' : router.asPath)
).split('?')[0]

// Then somewhere in your _app.tsx or top level layout component
return (
  <Head>
    <link rel="canonical" href={canonicalUrl} />
  </Head>
)
Darragh ORiordan

Hi! I'm Darragh ORiordan.

I live and work in Sydney, Australia building and supporting happy teams that create high quality software for the web.

I also make tools for busy developers! Do you have a new M1 Mac to setup? Have you ever spent a week getting your dev environment just right?

My Universal DevShell tooling will save you 30+ hours of configuring your Windows or Mac dev environment with all the best, modern shell and dev tools.

Get DevShell here: ✨ https://usemiller.dev/dev-shell


Read more articles like this one...

List of article summaries

#engineering

Open Telemetry in NextJs and NestJs

I wrote about how to use open telemetry with NestJs and React previously.

I wanted to add open telemetry to my NextJs app that calls a NestJs backend. The paradigm of SSR preferred by NextJs is a bit different than the CSR paradigm of React.

I’ll describe the differences and how I added open telemetry to NextJs that propagates to other backend APIs.

#engineering

Comparing next start and next standalone with docker

I wrote about how to use nextjs with docker.

I wanted to compare using next standalone like in the article and just using next start.

#engineering

Force RSA key support for Azure DevOps Git SSH

If you’re using Azure DevOps Git SSH you have to use an RSA key. This is because Azure DevOps doesn…

Comments