Frontend Next.js 13 App Directory: Applying Metadata

In the App Directory, you can modify the <head> HTML element using metadata instead of the traditional Head tag. Metadata can be defined in the layout.js or page.js files using export const metadata.

Explanation

layout.js

export const metadata = {
  title: { default: 'KAKAO.GG', template: '%s | KAKAO.GG' },
  description: 'KAKAO.GG! Tech Blog',
  keywords: ['IT', 'Coding'],
}

Various Options

Since there are various options available, use them when creating metadata.

  • Name
    generator
    Type
    Option
    Description

    Indicates the name of the software used

    <meta name="generator" content="Next.js">
    
  • Name
    applicationName
    Type
    Option
    Description

    Indicates the name of the web application

    <meta name="application-name" content="Next.js">
    
  • Name
    referrer
    Type
    Option
    Description

    Directs how the browser sends the HTTP Referrer header

    <meta name="referrer" content="origin-when-cross-origin">
    
  • Name
    keywords
    Type
    Option
    Description

    Defines keywords for the web page

    <meta name="keywords" content="Next.js,React,JavaScript">
    
  • Name
    authors
    Type
    Option
    Description

    Author information for the web page

    <meta name="author" content="cptkuk91"/>
    
  • Name
    colorScheme
    Type
    Option
    Description

    Basic color scheme related to browser UI

    <meta name="color-scheme" content="dark">
    
  • Name
    creator
    Type
    Description
    <meta name="creator" content="cptkuk91">
    
  • Name
    publisher
    Type
    Option
    Description

    Publisher or owner information of the app

    <meta name="publisher" content="cptkuk91">
    
nextjs13

Dynamic Metadata?

To leverage dynamic metadata, it's not sufficient to just use metadata. Therefore, you need to make use of generateMetadata.

Since there can be various titles and contents of posts, dynamic metadata needs to be applied.

You can apply it using generateMetadata.

Apply it to post/[id]/page.tsx instead of the layout.

When generating metadata with the code below, you can utilize the title of each post as the metadata title and description.

/app/post/[id]/page.tsx

const getPost = async (id: string) => {
const post: PostType | null = await prisma.post.findUnique({
    where: { id },
});
export const generateMetadata = async ({ params }: any): Promise<Metadata> =>
{
    const data = await getData(params.id)
    return {
        title: data.title,
        description: post?.snippet,
    }
}