Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Fri Jun 09 2023

Set title and description in Next.js from the App router

I have very recently added Next.js to this website, in order to achieve SSR and improve our SEO. I haven't really used it before, so I will call myself a noob, but I am learning new stuff every day. Personally, I think it is a great framework with great features and it works really well.

I will continue to post tutorials and guides for Next.js related features as I am adding new stuff to our application every day and are learning new stuff all the time.

In this guide, I will post a solution on how we can set title and description for each page that we have in our app folder.

Problem

The problem I faced, was that the title and description meta didn't update when I was navigating to a new page, I tried various things, such as the Head component that Next.js are providing, but no luck. The problem seemed to be for my pages that was using the use client directive.

Solution

So after some hours of trying different things, I found a solution. In order to get it to work, I used the metadata object and a function called generateMetadata for the dynamic meta data. And I added them to the layout.tsx file, which I also added for all my pages.

So, in all my sub-folders in the app directory, I had one page.tsx and one layout.tsx, and in the layout, I added following code for the pages with static meta data:

import { Metadata } from "next"; import CommonLayout from "components/CommonLayout"; export const metadata: Metadata = { title: "Free APIs and front end solutions - Algobook", description: "Free APIs and software solutions for student projects, side projects or small organisations", }; export default function PageLayut({ children }: { children: React.ReactNode }) { return ( <> <CommonLayout>{children}</CommonLayout> </> ); }

And for the pages where I wanted dynamic titles and description, I added this:

import CommonLayout from "components/CommonLayout"; export async function generateMetadata({ params }: any) { const dynamicData = await fetch("..."); return { title: `${dynamicData.myTitle} - Algobook`, description: `${dynamicData.someText}`, }; } export default function PageLayut({ children }: { children: React.ReactNode }) { return ( <> <CommonLayout>{children}</CommonLayout> </> ); }

And after that, it all worked as a charm!

Summary

In this short guide, I presented my solution on how to get titles and description on all my pages in my Next.js application. As stated, I am very new to this framework, and are still learning. So if you have any feedback, or if you see things that could be improved, please contact me here.

I will continue to add articles and tutorials for Next.js, so stay tuned. And have a great day!

signatureFri Jun 09 2023
See all our articles