When developing a web application with Next.js, managing page titles can become a bit of a hassle. As your project expands, you want a system in place that handles <title> titles smoothly and prevents those all-too-common mistakes, like a misspelled brand name.

I'm going to show you how to set up a Page component that's type-safe, ensuring your browser tab titles stay consistent and free from typos.

Our Goals

  • Set the <title> tag through a property in a React component in Next.js framework.
  • Have the flexibility to set either just the brand name Steady Cursor for our homepage, avoiding the redundant Home | Steady Cursor.
  • For regular pages like contacts or catalog, we want to include the page name followed by a divider and then the brand name (example: Contact | Steady Cursor).
  • Ensure we never misspell the brand name or forget the divider.
  • Create a universal solution by implementing it into a Page component, which will be reused on every page.

Solution

We use TypeScript to make sure our titles are always right. This means we can have just Steady Cursor for our main page or Something | Steady Cursor for other pages. TypeScript will tell us if we forget the divider or make a spelling mistake in our brand name.

Here's a sample of the final code:

import { ReactNode } from "react";
import Head from "next/head";

export type PageProps = {
	title: string | null;
	headTitle: `${string} | Steady Cursor` | "Steady Cursor";
	children: ReactNode;
};

export const Page = ({ title, headTitle, children }: PageProps) => {
	return (
		<div>
			<Head>
				<title>{headTitle}</title>
			</Head>
			{title && <h1>{title}</h1>}
			{children}
		</div>
	);
};

Usage

We can use the component:

  • <Page title="Contact" headTitle="Contact us | Steady Cursor"></Page> for sub-pages
  • <Page title={null} headTitle="Steady Cursor"></Page> for homepage.

Tests for headTitle property

Below are the values I tested with the Page component. It's evident that Typescript flags values not meeting our requirements as errors.

Tested values:

  • ✅ Steady Cursor
  • ✅ Contact | Steady Cursor
  • ✅ About us | Steady Cursor
  • 🚨 Steady Crsor
  • 🚨 About Us|Steady Cursor
  • 🚨 Contact| Steady Cursor
  • 🚨 Lear |Steady Cursor
  • 🚨 Blog | Sady Cursor

Conclusion

Creating a type-safe Page component in Next.js not only makes managing page titles easier across your application but also keeps common mistakes at bay.

With TypeScript, you can present your brand consistently and professionally right in the browser tabs, which often create the first impression for your visitors.

This is one of the best uses of template string literals I've seen. It's not limited to this case alone, and it's an elegant solution that enhances the reliability of your application.

Source code is available on GitHub

The entire episode is available on YouTube

Do not miss a thing!