NextJS provides complete control over the page we wish to render. While we can create individual pages of our application, NextJS also allows us to customize the entire HTML document if needed. In this post, we will learn how to use the NextJS DocumentJS file for customizing the HTML document itself.

In case you are a beginner to NextJS, check out this post on getting started with NextJS.

1 – NextJS DocumentJS File

Every NextJS application has a root component file known as _app.js. Basically, this file is like an application shell within which our page components are rendered.

However, sometimes we want to update even the basic HTML layout with <html> and <body> tags. For this purpose, we can create a custom file by name _document.js within the pages folder.

See below example:

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

class MyDocument extends Document {
    render() {
        return (
            <Html lang="en">
                <Head />
                <body>
                    <Main />
                    <NextScript />
                </body>
            </Html>
        );
    }
}

export default MyDocument;

Here, we have to use a class component since we have to extend the Document component. The Document component is part of the next/document library.

Apart from the importing the Document class, we also import other components such as Html, Head, Main, NextScript from next/document.

Using these components, we create the default structure of our HTML document. We can also add custom attributes as props. For example, we supply the lang="en" as a prop to the Html component. This makes sure that the final rendered HTML will have the proper value for lang.

Also, we can add a specific CSS class to other tags such as body.

Note that the _document.js file is rendered only on the server. Therefore, we can add other event handlers such as click handlers.

Conclusion

All in all, the _document.js file is a great way to customize the overall HTML page layout. We can also declare some specific elements within this file to make them available for all the pages.

Want to learn more about NextJS? Check out this post on NextJS file-based routing.

If you have any comments or queries about this post, please feel free to mention them in the comments section below.

Categories: NextJS

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *