Customizing the _app.js and _document.js Pages
Learn to customize page initialization and HTML tags and to extend the Document class with custom scripts.
We'll cover the following...
There are certain cases where we need to take control over page initialization so that every time we render a page, Next.js will need to run certain operations before sending the resulting HTML to the client. To do that, the framework allows us to create two new files, called _app.js
and _document.js
, inside our pages/
directory.
The _app.js
page
By default, Next.js ships with the following pages/_app.js
file:
import "../styles/globals.css";function MyApp({ Component, pageProps }) {return <Component {...pageProps} />;}export default MyApp;
As we can see, the function is just returning the Next.js page component (the Component
prop) and its props (pageProps
).
But now, let’s say that we want to share a navigation bar between all the pages without manually importing that component on each page. We can start by creating the navbar inside components/Navbar.js
:
import Link from "next/link";function Navbar() {return (<divstyle={{display: "flex",flexDirection: "row",justifyContent: "space-between",marginBottom: 25,}}><div>My Website</div><div><Link href="/">Home </Link><Link href="/about">About </Link><Link href="/contacts">Contacts </Link></div></div>);}export default Navbar;
That’s a really simple navigation bar with just three links that will allow us to navigate our website.
Now, we need to import it inside our _app.js
page as follows:
import "../styles/globals.css";import Navbar from "../components/Navbar";function MyApp({ Component, pageProps }) {<Navbar />;return <Component {...pageProps} />;}export default MyApp;
If we now ...