Defining a Custom Document in Next.js

next js custom document setup
01 December 2024

Using Next.js for Managing Routes


Next.js, being one of the best React frameworks, offers numerous possibilities for managing routes with the help of the Page Router. This feature assists us in creating web applications with an appropriate structure and user-friendly interface. One of the benefits of using Custom Document pages is that we can directly connect to the structure of HTML files and execute specific configurations such as adding meta tags common to all pages. This article aims to remind you how to create a Custom Document in a Next.js project and benefit from it.


In Next.js, the _document.js file allows you to change the base HTML template for all pages of your site. This feature enables you to add meta tags, or use custom functionalities. While many capabilities can function without needing to edit this file in Next.js, the HTML structure is always customizable.



To get started, you need to create a new file named _document.js in the /pages directory. In this file, define your component as follows:


import Document, { Html, Head, Main, NextScript } from 'next/document';

class MyDocument extends Document {
render() {
return (
<Html>
<Head>
<!-- custom configurations and meta tags here -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}

export default MyDocument;

Here is a line-by-line explanation of the declared code:


import Document, { Html, Head, Main, NextScript } from 'next/document';
This is where you start your file by importing the necessary modules from Next.js.


class MyDocument extends Document {
The class MyDocument is created extending Document, allowing you to modify the default HTML structure.


render() {
The render method is responsible for generating the HTML content.


Within return ( ... )
, the HTML structure that needs to be rendered is defined.


<Html>
This tag indicates the beginning of the HTML structure of the document.


<Head></Head>
This tag includes all additional HTML tags that must be present on every page.


<body></body>
This tag indicates the main content of the page, which is populated by the Main and NextScript tags.

FAQ

?

Why should I use a Custom Document in Next.js?

?

Is editing the _document.js file necessary in Next.js?