I’m new to next.js
I don’t understand why metadata variable is exported from Layout file and not importing it anywhere
import "./globals.css";
export const metadata = {
title: "NextJS App",
description: "Your first NextJS app!",
};
export default function Layout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
I’m learning through the course and documentation and Google.
Not found any idea behind this !!
Guys please do comment !!
Thanks
2
Answers
Next.js uses the
metadata
object orgenerateMetadata()
function to define the metadata for the corresponding page or layout.You don’t need to import this anywhere. Next.js will automatically read this and insert the relevant tags in the page’s
<head>
section.You typically use metadata for pages to help search engines index your page appropriately. You also use it to display previews in social media platforms like Facebook or X.
Here’s more information on what you can define as metadata for your page.
In your example, since you’re using the root layout, any page in your application will have the following tags:
I think you already knew what meta tags are for, and the doubt would be regarding not importing them anywhere in the code.
Well, take a look at your code, you also export the layout, and you don’t import it anywhere, the same goes for the pages inside the routes: e.g.:
'app/dashboard/page.tsx'
(although you can import them).
This is part of the framework architecture, Next.js relies on a convention-based approach to automatically generate routes based on the file system structure in the directory.
When you export the default component from a file, you are essentially telling Next.js that this component is associated with a specific route in your application. The same goes for meta tags, Next.js will automatically generate the appropriate elements for your pages.
You can also export the metadata from
page.tsx
files. Consequently, there may be several metadata exports for several segments on the same route. In these cases, the metadata objects are combined to generate the final metadata output for a route. Duplicate keys are replaced from the root segment to the segment closest to the final page.js segment.So basically, the act of exporting the metadata from the layout file plays a role in the background operations of the framework, contributing to the creation of the final metadata output for your routes. Even if you don’t import them directly, their presence and structure are used by Next.js
I hope I was able to help! 🙂