Nextjs application routers offer dynamic routing functionality and the ability to generate metadata

Struggling with static site generation while building a blog site in nextjs with app router? If you've read through Next.js official documentation and still need assistance, check out my project structure pictured https://i.stack.imgur.com/ZOYkf.png. Inside my project, I have a file named blogData.js where I store all the blog data.

import { FullStackDeveloper, GraphicDesigner } from "@/assets/team";
    
    const BlogData = [
      {
        id: 0,
        title: "Exploring the Power of React.js for Interactive Web Applications",
        cover: FullStackDeveloper,
        desc: "Delve into the incredible capabilities of React.js for creating dynamic and interactive web applications. Discover how React.js enhances user experience, improves performance, and enables seamless data management. Gain insights into the benefits and best practices of using React.js for your next web development project.",
        keywords: [
          "React.js",
          "interactive web applications",
          "user experience",
          "performance",
          "data management",
          "web development",
          "best practices",
        ],
        date: "23rd Jun 2023",
        url: "exploring-the-power-of-react-js-for-interactive-web-applications",
      },
      {
        id: 1,
        title: "Mastering the Art of Design: Unleashing Creativity and Aesthetics",
        cover: GraphicDesigner,
        desc: "Explore the world of design and discover strategies to unlock your creativity. Learn about the principles of effective design, color theory, typography, and user-centered design. Unleash your artistic potential and create visually stunning experiences.",
        keywords: [
          "design",
          "creativity",
          "aesthetics",
          "color theory",
          "typography",
          "user-centered design",
          "visual experience",
        ],
        data: "25th Jun 2023",
        url: "mastering-the-art-of-design-unleashing-creativity-and-aesthetics",
      },
    ];
    
    export { BlogData };

My layout.js file contains:

export const metadata = {
  title: "dynamic blogs",
  description: "dynamic descriptions",
};
export default function layout({ children }) {
  return (
    <>
      {children}
    </>
  );
}

For the blog page functionality, here is my page.js code:

export default function page({ params }) {
  return (
    <>
      <div className="overflow-hidden bg-white text-black md:py-20">
        <div className="container relative mx-auto px-4">
          <div className="grid grid-cols-1 items-center px-4 py-20 xl:py-10">
            <div>
              <h1 className="relative z-10 text-center text-6xl font-bold xl:text-9xl">
                Welcome to
                <br />
                Our Blog
              </h1>
              <span className="absolute top-0 w-full transform whitespace-nowrap text-center text-[250px] font-extrabold text-gray-400 opacity-30 blur-[1px] ">
                BLOGS
              </span>
              <p className="mx-auto mt-10 text-center text-base xl:w-2/3 xl:text-2xl">
                Explore a wide range of topics on our blog, covering web
                development, design, digital marketing, and technology. Stay
                updated with industry trends, practical tips, and expert
                insights. Discover the latest techniques and technologies in web
                development, get inspired by design trends, learn digital
                marketing strategies, and stay informed about emerging
                technologies. Join our community and empower yourself with
                knowledge and inspiration.
              </p>
            </div>
          </div>
          {/* <h1>id : {}</h1> */}
          <h1>Title : {params.desc}</h1>
        </div>
      </div>
    </>
  );
}

If you're struggling with generating titles and descriptions based on URL from blogData.js, maybe consider revisiting the generateStaticParams function mentioned in the Next.js official documentation for better results.

Answer №1

If you're looking to optimize your blog pages, consider utilizing generateMetaData for each individual page.

Alternatively, you can statically define metadata for specific pages such as /blogs and /blogs/***.

/app/blogs/layout.js

import { Metadata } from 'next';
import * as React from 'react';
export const metadata = {
  title: {
    default: 'dynamic blogs',
    template: `%s - Blog`,
  },
  description: 'dynamic description'
}
....

/app/blogs/[blogTitle]/layout.js

import { Metadata } from 'next';
import * as React from 'react';
export const metadata = {
  title: 'Content',
  description: 'Blog Description'
}
.... 

This will result in the title being 'Content - Blog' for routes like '/blogs/****'.

Make sure to define metadata in layout.js files rather than page.js. Although both options are mentioned in the documentation, I have found that only one (layout) works effectively.

For better code organization, consider restructuring your blog website following this file structure:

https://i.stack.imgur.com/5yeJE.png

and then update the layout.js like so /app/blogs/[id]/layout.js

import { Metadata } from 'next';
import * as React from 'react';
import { BlogData } from '../../blogData.js';     // make sure to update this path

export async function generateMetadata({ params }, parent) {
  const id = params.id;

  const blog = BlogData.find(item => item.id === id);

  return {
    title: blog.title,
    description: blog.description,
    keywords: blog.keywords
  };
}
....

I hope these suggestions prove helpful for you.

Answer №2

If you want to create dynamic metadata, make use of the generateMetadata function:

When your metadata needs to change based on dynamic factors like current route parameters, external data, or inherited metadata, you can define a generateMetadata function that outputs a Metadata object.

An illustration is given in the provided link. Implement your code within a try/catch block to manage potential errors effectively:

import { Metadata, ResolvingMetadata } from 'next'
 
type Props = {
  params: { id: string }
  searchParams: { [key: string]: string | string[] | undefined }
}
 
export async function generateMetadat(
  { params, searchParams }: Props,
  parent: ResolvingMetadata
): Promise<Metadata> {
  try {
    const id = params.id;

    // fetching data
    const product = await fetch(`https://.../${id}`).then((res) => res.json());

    // optionally modifying existing parent metadata
    const previousImages = (await parent).openGraph?.images || [];

    return {
      title: product.title,
      openGraph: {
        images: ["/some-specific-page-image.jpg", ...previousImages],
      },
    };
  } catch (error) {
    return {
      title: "Not Found",
      description: "The page you are looking for does not exist",
    };
  }
}
 
// now proceed with writing your page 
export default function Page({ params, searchParams }: Props) {}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Material UI/React - unable to display helper text

My login react component is not showing the 'wrong credentials' error in the helper text even when false credentials are entered. I am pushing an error message into an array, assigning it to state, and then referencing that state in my helperText ...

Creating an interactive /robots.txt file for a Next.js application

I'm looking for a solution to dynamically respond to the /robots.txt request. To achieve this, I have chosen to utilize getServerSideProps https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering By exporting a ...

Error in parsing: Looking for the correct JSX closing tag for <Route>?

Having trouble linking my car page so that it redirects to the correct location. I am encountering an error message indicating a JSX closing tag for route, even though all tags appear to be properly closed. Can't figure out why this error keeps occurr ...

How exactly does the NextAuth User Password implementation function?

I am currently working on implementing user authentication using NextAuth with email only. My goal is to have users register an account, receive an account verification email, and then successfully register. It seems that using NextAuth would be the most c ...

The command `node server.js` has been initiated. Nodemon has executed a clean exit and is now waiting for any

A React application has been developed where users can input their email and a message to send to the server. However, upon trying to send the message, Error number 2 is encountered along with viewing Error number 1 in the terminal. Despite ensuring that ...

Is it necessary for the React generic type prop to be an extension of another type

I have recently started using TypeScript and I am facing a confusion regarding passing generic types into my higher-order component (HOC). My objective is to pass the component props as a generic type in order to have the Component with those specific type ...

What is the best way to trigger a function in React when a constant value is updated?

In my React application, I have 3 components. The parent component and two child components named EziSchedule and EziTransaction. Each component fetches its own data from an API. The data to display in the EziTransaction child component depends on the reco ...

Design your own arrow Slideshow + Next.js + Sass styling

In my current project, I am utilizing the swiper slider within a Next.JS development environment and styling with Sass. However, despite following the documentation guidelines to apply custom styles to the slider arrows, they do not display correctly. My ...

Webstorm showcases files with similar content in a distinct manner

In Webstorm, everything is color-coded based on whether it is a function, object, etc. I am working with JavaScript. I have noticed that in two different files, the same line of code looks differently: var Comment = React.createClass({ In file 1: "var" ...

How can I bring in a dynamic MaterialUI theme object from another file?

Could anyone provide guidance on the correct syntax for importing a dynamic theme object from a separate file? I am attempting to retrieve the system theme based on a media query and then dynamically set the theme. Everything works as expected when all t ...

Achieving Material-UI functionality in Reactjs without the need for Node.js or NPM

Are there any alternative sources for a minified version of material-ui specifically designed for React? I am considering including the jsx files in html externally, so I'm curious if there are any static or CDN resources available besides the tradit ...

Tips for resolving the "Page Not Found" error in your NextJs application

I am organizing my files in the following structure src/ ├── app/ │ ├── pages/ │ │ ├── authentication/ │ │ │ ├── SignUp/ │ │ │ │ └── page.tsx │ │ │ └── SignIn/ │ ...

Prevent entry to a specific directory within NextJS

Is there a method to restrict access to the directory in NextJS? For instance, if I wish to prevent access to the directory /public/images? In that case, I would serve images through api routes. So, the image would be displayed in a component like this: & ...

Error message in Typescript with React: "The type 'ComponentClass<StyledComponentProps<{}>>' cannot be assigned to type 'typeof MyComponent'"

Currently experimenting with integrating the Material UI 1.0 (beta) @withStyles annotation into a React component. The documentation provides a JavaScript example (), however, it results in a compilation error when using Typescript. Despite the error, the ...

Uploading base64 images to Azure Storage using Next.js is a breeze!

After attempting various alternatives to solve this issue, I discovered that many of them are outdated. Even though the code below runs without any errors and successfully uploads the image while setting the mimetype correctly, it fails to render as an ima ...

Having trouble compiling MDX files that include React Components?

I have implemented NextJS and MDX using next-mdx-remote to retrieve my data, and it's working successfully. However, I encounter an error whenever I try to import React components: Error: Expected component CodeBlock to be defined: you likely forgot ...

How to correctly pass a function between components in React using TypeScript

Having just started learning typescript, I encountered difficulties passing a function from the parent component to another component as a prop. Despite searching online for solutions, I couldn't find anything helpful. Here is the JSX Code for refere ...

Every time the submit button is clicked, I aim to store an object in an array. However, currently, only a single object is being stored in the array after

I am trying to store user objects in an array after each submit button click, but it currently only stores a single object and returns it. import React from 'react'; import {useHistory} from 'react-router-dom' import {useEffect} from ...

Max Savings Seeker API Version Four

Currently, I am working on incorporating the Bargain Finder Max Rest API into my Node.js application. However, the data being returned is not as complete or useful as I had hoped. Does anyone have any suggestions on how to obtain more comprehensive data? D ...

Applying CSS to an iframe using JavaScript: A Step-by-Step

I have an Iframe editor and I am trying to change some CSS inside the editor. However, when I attempt to apply the CSS, it does not affect the styles within the Iframe. <div id="editor" style="flex: 1 1 0%;"> <iframe src="https://editor.unlay ...