Next.js 15 Tutorial - 17 - Routing Metadata
Search Engine Optimization with Nex.js
Overview of Metadata API in Nex.js
- The metadata API in Nex.js allows users to define metadata for each page, enhancing how content appears when shared or indexed by search engines.
- There are two methods to handle metadata: exporting a static metadata object or a dynamic generate metadata function from layout. TSX or page. TSX files.
Key Points on Configuring Routing Metadata
- Layout metadata applies to all pages, while page-specific metadata is unique to that page.
- Metadata follows a top-down order; if multiple metadata objects exist along the route, they merge, with page metadata overriding layout metadata for matching properties.
Static Metadata Object Approach
- In the root layout. TSX file, a static metadata object can be exported with properties like title and description.
- When navigating to different routes (e.g., about code Evolution), the title changes based on deeper segments taking priority over root layout titles.
Dynamic Metadata Configuration
- Dynamic metadata is useful when it relies on changing information such as current route parameters or external data.
- A generate metadata function can be defined in page. TSX files to create unique titles for items like products based on their IDs.
Implementing Generate Metadata Function
- The function receives parameters and returns a promise of type metadata, allowing for dynamic title generation based on product ID.
- An example shows how fetching product details could dynamically set the title; however, this example uses a simple promise delay instead of an actual API call.
Limitations and Best Practices
- You cannot use both a static metadata object and a generate metadata function within the same route segment; only one method is allowed.
- Pages marked with the use client directive cannot export any form of metadata due to restrictions; it's essential to keep server components separate from client-side logic.
Correct Pattern for Client-Side Logic
Importing and Rendering the Counter Component
Steps to Import and Render
- The counter component is imported at the top of the file, ensuring it is available for use in the return statement.
- The directive
use Centis removed from the code, simplifying the component's structure.
- The
useStatehook is also eliminated, but the metadata object remains intact for proper functionality.
- Upon refreshing the SLC counter route, users will see a rendered page displaying the counter title without any errors.