Questions
What is the `_document.js` file and what is it used for in Next.js?
The Scenario
You are a frontend engineer at a social media company. You are building a new Next.js application and you want to add some custom <html> and <body> tags to your application.
You are not sure where to put these tags.
The Challenge
Explain what the _document.js file is in Next.js and how you would use it to solve this problem. What are the key benefits of using the _document.js file?
A junior engineer might not be aware of the `_document.js` file. They might try to solve this problem by adding the tags to each page, which would not be a very good solution.
A senior engineer would know that the `_document.js` file is the perfect tool for this job. They would be able to explain what the `_document.js` file is and how to use it to add custom `<html>` and `<body>` tags to the application.
Step 1: Understand What the _document.js File Is
The pages/_document.js file is a special file in Next.js that allows you to override the default Document component.
Step 2: The Key Use Cases for the _document.js File
| Use Case | Description |
|---|---|
Custom <html> and <body> tags | To add custom <html> and <body> tags to your application. |
| Server-side rendering | To add server-side rendering logic to your application. |
Step 3: Solve the Problem
Here’s how we can use the _document.js file to add custom <html> and <body> tags to our application:
// pages/_document.js
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 MyDocumentIn this example, we have added a lang="en" attribute to the <html> tag.
_app.js vs. _document.js
| File | Purpose |
|---|---|
_app.js | To initialize pages. This is the place to add a global stylesheet or a layout component. |
_document.js | To augment the <html> and <body> tags. This is the place to add a lang attribute or a custom font. |
Practice Question
You want to add a global stylesheet to your application. Which of the following would you use?