Note: this post is valid as of Next 13 (not beta).
Two of the most important files in a Next.js project are _app.js
and _document.js
. Both of these files can play
and important role in the server side rendering process, but they serve different purposes.
In this blog post, we will explore the differences between _app.js
and _document.js
and when to use each.
_app.js
acts as the wrapper for all other pages. It does this by creating a custom React component for every page. This component can be used to add global styles, set up the Redux store, and define other custom behaviors that should be applied to all pages.
Here's an example of a basic _app.js
file:
import "../styles/globals.css"; function MyApp({ Component, pageProps }) { return <Component {...pageProps} />; } export default MyApp;
In this example, we import a global stylesheet and create a function component that receives two props: Component and pageProps. The Component prop represents the page component that should be rendered, and the pageProps prop contains any props that were passed to that page.
By default, the _app.js
file is empty, and all pages are rendered with the default Next.js behavior. However, you can customize the behavior of the _app.js
file to add your own customizations like above.
_document.js
is another special file in Next.js that is responsible for setting up the HTML document that is served to the browser. This file is only executed on the server and is used to add custom <head> and <body> tags to the HTML document.
Here's an example of a basic _document.js
file:
import Document, { Html, Head, Main, NextScript } from "next/document"; class MyDocument extends Document { render() { return ( <Html> <Head> <meta charSet="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="/css/main.css" /> </Head> <body> <Main /> <NextScript /> </body> </Html> ); } } export default MyDocument;
In this example, we create a new class component that extends Document. In the render method of the component, we define the custom <head> and <body> tags that should be included in the HTML document. We also import an external stylesheet and add a reference to it in the <head> tag.
Just like with _app.js
, the _document.js
file is optional, and you can use it to add customizations to the HTML document that is served to the browser.
In summary, _app.js
and _document.js
are two special files in Next.js that play different roles. _app.js
is responsible for creating a custom wrapper component that applies to all pages in the application, while _document.js
is responsible for setting up the HTML document that is served to the browser.