nextjs custom document
Create a new file called
_document.js
in thepages
directory of your Next.js project.Import the necessary dependencies at the top of the file. These dependencies include
Document
from thenext/document
module andHtml
,Head
, andMain
from thenext/document
module.Create a new class called
MyDocument
that extends theDocument
class.Inside the
MyDocument
class, define a static method calledgetInitialProps
. This method takes a parameter calledctx
and returns a promise that resolves to an object containing thehtml
,head
, andstyles
properties.In the
getInitialProps
method, call theDocument.getInitialProps
method with thectx
parameter and store the result in a variable calledinitialProps
.Create a new variable called
styles
and assign it the value ofinitialProps.styles
.Return an object containing the
html
,head
, andstyles
properties, with their respective values set toinitialProps.html
,initialProps.head
, andstyles
.Below the
MyDocument
class definition, export theMyDocument
class as the default export of the file.
By following these steps, you will create a custom document file in Next.js that allows you to customize the HTML document structure and add any required global CSS styles.