How to add custom document in nextJs 13 – Javascript

by
Alexei Petrov
next.js next.js13 reactjs

The Problem:

A user wants to incorporate a custom document in their next.js 13 project. They plan to utilize a custom design system package that mandates custom documents to be placed in the page directory, as suggested in the next.js documentation. However, they have noticed that there is no designated location for custom documents in the app directory structure of next.js 13. They seek guidance on how to address this issue.

The Solutions:

Solution 1: Create a Root Layout

In Next.js 13, you can create a root layout called `app/layout.tsx` (or `app/layout.js` if you’re not using TypeScript) to replace the `_app.js` and `_document.js` files from the `pages` router. This root layout applies to all routes and enables you to modify the initial HTML returned from the server.

Here’s an example of a simple root layout in app/layout.tsx:

import React from "react";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Next.js App</title>
      </head>
      <body>{children}</body>
    </html>
  )
}

This layout provides a basic HTML structure with a head and body section. You can then use it to wrap your app’s content within the children prop, like so:

In pages/index.js:

import RootLayout from '../app/layout';

export default function Home() {
  return (
    <RootLayout>
      <h1>Home Page</h1>
    </RootLayout>
  )
}

By using a root layout, you can easily apply customizations to your entire app’s HTML without having to modify individual pages. This is especially useful for implementing a custom design system or making global changes to the HTML structure.

Q&A

How to create custom document in nextjs 13

Use the app/layout.tsx file (also called root layout) in the app directory.

What is the purpose of root layout?

To modify the initial HTML returned from the server.

How about app/layout.js?

If you are not using TypeScript, you can use the file app/layout.js.

Video Explanation:

The following video, titled "Custom Document Page in Next.js - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

... document's markup. To override the default Document, create the file ./pages/_document.js and extend the Document class as shown below: Next.js ...