Setting Titles Dynamically with Next.js Metadata
Tags: nextjs, seo, web, learning
Published: 2024-07-09 06:50:01

Next.js has introduced a new App Router that provides more flexibility and structure to manage routes and metadata. This new approach simplifies dynamic title setting and other metadata for your application. In this blog post, we'll explore how to set titles dynamically using the App Router in Next.js.

**Why Dynamic Titles Matter**
Dynamic titles enhance the user experience by providing relevant information for each page. They also improve SEO, making it easier for search engines to index your pages accurately. This is particularly important for content-heavy websites like blogs, e-commerce stores, and news sites where each page has unique content.

**Getting Started with the App Router**
-First, ensure you have a Next.js project set up with the App Router. If not, you can create one by running:

```
npx create-next-app@latest
```
-Navigate to your project directory:

```
cd your-nextjs-app
```

Ensure your Next.js version supports the App Router. The App Router is available from Next.js 12.1 onwards.

**Using Metadata in App Router**
Next.js App Router uses a special metadata property to handle the <head> tags, including the title. This method allows you to define metadata in your page components directly.

**1.Create Your App Layout:**
In the app directory, create a layout file (e.g., app/layout.js):

```
// app/layout.js
import './globals.css';

export const metadata = {
  title: 'Default Title - My Next.js App',
  description: 'Default description for my Next.js app',
};

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <head />
      <body>{children}</body>
    </html>
  );
}
```


**2.Set Dynamic Titles in Page Components:**
Each page component can override the default metadata by exporting a metadata object. Here's an example for a home page:

```
// app/page.js
export const metadata = {
  title: 'Home Page - My Awesome Website',
  description: 'Welcome to the home page of my awesome website',
};

export default function HomePage() {
  return (
    <div>
      <h1>Welcome to My Awesome Website</h1>
    </div>
  );
}

```

**3.Dynamic Titles Based on Props:**
For more dynamic use cases, such as blog posts or product pages, you can set the title based on props. Here’s an example for a blog post page:

```
// app/posts/[id]/page.js
import { useRouter } from 'next/router';

export async function generateMetadata({ params }) {
  const { id } = params;
  const res = await fetch(`https://api.example.com/posts/${id}`);
  const post = await res.json();

  return {
    title: `${post.title} - My Blog`,
    description: post.summary,
  };
}

export default function BlogPost({ params }) {
  const { id } = params;
  const [post, setPost] = React.useState(null);

  React.useEffect(() => {
    fetch(`https://api.example.com/posts/${id}`)
      .then((response) => response.json())
      .then((data) => setPost(data));
  }, [id]);

  if (!post) return <div>Loading...</div>;

  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </div>
  );
}

```

**Advanced Metadata Handling**
For more complex scenarios, you might want to set metadata dynamically at a global level or use custom hooks. The following example demonstrates a custom hook for managing metadata:
**1.Create a Custom Hook:**

```
// hooks/useMetadata.js
import { useEffect } from 'react';
import { useRouter } from 'next/router';

const useMetadata = (title, description) => {
  const router = useRouter();

  useEffect(() => {
    document.title = title;
    const metaDescription = document.querySelector('meta[name="description"]');
    if (metaDescription) {
      metaDescription.setAttribute('content', description);
    } else {
      const meta = document.createElement('meta');
      meta.name = 'description';
      meta.content = description;
      document.head.appendChild(meta);
    }
  }, [title, description, router.pathname]);
};

export default useMetadata;
```

**2.Use the Hook in a Component:**
```
// app/page.js
import useMetadata from '../hooks/useMetadata';

export default function HomePage() {
  useMetadata('Home Page - My Awesome Website', 'Welcome to the home page of my awesome website');

  return (
    <div>
      <h1>Welcome to My Awesome Website</h1>
    </div>
  );
}
```


**Conclusion**
Setting dynamic titles and metadata in Next.js using the App Router is straightforward and powerful. By leveraging the metadata property and custom hooks, you can ensure that each page in your application has the correct metadata, improving both SEO and user experience. Experiment with different strategies to see what works best for your use case, and remember that thoughtful metadata can significantly impact your site's visibility and user engagement.

Happy coding!