iTranslated by AI
Important considerations for using next/router with pages undergoing Automatic Static Optimization
Article Overview
This article explains why caution is required when using query or asPath from next/router on pages that have undergone Automatic Static Optimization. While the content is as described in the official documentation, it was difficult to grasp without prior knowledge, so I decided to provide an easy-to-understand explanation.
The current version of Next.js is 12.2, which is the latest as of this writing.
Target Audience
This is written for those who have just started using Next.js and struggle to understand the official documentation due to a lack of background knowledge.
Keywords
- Automatic Static Optimization
- Pre-rendering
- Hydrate
What is Automatic Static Optimization?
Automatic Static Optimization is a feature where, during the build process, pages that do not involve server-side processing (i.e., they do not have getServerSideProps or getInitialProps) are generated as HTML files, while other pages are generated as JS files. Instead of building the entire application, it optimizes the build on a per-page basis. By performing per-page optimization, pages without server-side processing can return ready-to-render HTML, which improves response speed. The HTML generated here is in a state called Pre-rendering, which is explained later.
What is Pre-rendering?
Pre-rendering refers to returning HTML that is already ready to render, rather than generating the entire HTML via client-side JS. For pages without server-side processing, the HTML generated during the build is returned; for other pages, the server dynamically returns Pre-rendered HTML.
What is Hydrate?
Hydrate refers to attaching React event listeners to the Pre-rendered HTML in the context of Next.js. Each element of the Pre-rendered HTML is assigned an ID to map it to the React virtual DOM.
Precautions for next/router
With the prerequisite knowledge covered, the rest is straightforward.
1. The query object will be {} in HTML (Pre-rendering) generated by Static Optimization
Automatic Static Optimization is a process that occurs during the build. Since there are no query strings available at build time, it will be {}.
To reference query, you must wait until the initial client-side rendering (Pre-rendering) is complete. You can detect this by monitoring changes to router.isReady within a useEffect hook.
2. Do not embed asPath into HTML (Pre-rendering) generated by Static Optimization
asPath includes the query string in the path, so the same logic as query applies.
Because there is no query string at the time of Automatic Static Optimization, if you reference it during Pre-rendering and embed it into the DOM, it will result in a string different from the path actually requested.
The workaround is the same as for query: use useEffect to detect when router.isReady becomes true before referencing it.
Verification
Let's verify this by creating a fresh Next.js project using create-next-app.
npx create-next-app@latest --ts
1. Behavior of Automatic Static Optimization
First, let's build the initial project. It might be hard to see, but there is a ○ to the left of / in the output. This indicates that HTML for the / page was generated during the build.
npm run build
(output truncated)
Page Size First Load JS
┌ ○ / 5.42 kB 83.1 kB
├ └ css/ae0e3e027412e072.css 707 B
├ /_app 0 B 77.7 kB
├ ○ /404 186 B 77.8 kB
└ λ /api/hello 0 B 77.7 kB
+ First Load JS shared by all 77.7 kB
├ chunks/framework-db825bd0b4ae01ef.js 45.7 kB
├ chunks/main-f0e16f48d3775e5e.js 30.7 kB
├ chunks/pages/_app-deb173bd80cbaa92.js 499 B
├ chunks/webpack-7ee66019f7f6d30f.js 755 B
└ css/ab44ce7add5c3d11.css 247 B
λ (Server) server-side renders at runtime (uses getInitialProps or getServerSideProps)
○ (Static) automatically rendered as static HTML (uses no initial props)
Next, let's add getInitialProps and build again.
// getInitialProps that does nothing
Home.getInitialProps = () => {
return {};
}
Now, λ is displayed to the left of /. This indicates that JS for the / page was generated during the build.
npm run build
(output truncated)
Page Size First Load JS
┌ λ / 5.43 kB 83.1 kB
├ └ css/ae0e3e027412e072.css 707 B
├ /_app 0 B 77.7 kB
├ ○ /404 186 B 77.8 kB
└ λ /api/hello 0 B 77.7 kB
+ First Load JS shared by all 77.7 kB
├ chunks/framework-db825bd0b4ae01ef.js 45.7 kB
├ chunks/main-f0e16f48d3775e5e.js 30.7 kB
├ chunks/pages/_app-deb173bd80cbaa92.js 499 B
├ chunks/webpack-7ee66019f7f6d30f.js 755 B
└ css/ab44ce7add5c3d11.css 247 B
λ (Server) server-side renders at runtime (uses getInitialProps or getServerSideProps)
○ (Static) automatically rendered as static HTML (uses no initial props)
2. What happens if you embed query or asPath in HTML built with Static?
Let's try extracting the values of query and asPath without using getInitialProps as follows:
import { useRouter } from 'next/router'
const Home: NextPage = () => {
const { query, asPath } = useRouter()
return (
<div className={styles.container}>
<p>q: {query.q}</p>
<p>asPath: {asPath}</p>
</div>
)
}
The built HTML will look like this (formatted for readability):
<body>
<div id="__next">
<div class="Home_container__bCOhY">
<p>q: </p>
<p>asPath:
<!-- -->/
</p>
</div>
</div>
</body>
If you access this with a query string like http://localhost:3000/?q=hello, an error such as Error: Text content does not match server-rendered HTML. will occur.
To avoid this, use useEffect to extract the values only after isReady becomes true.
const Home: NextPage = () => {
const { isReady, query, asPath } = useRouter()
const [q, setQ] = useState<string>('')
const [currentPath, setCurrentPath] = useState<string>('')
useEffect(() => {
if (!isReady) return;
setQ(query.q as string)
setCurrentPath(asPath)
}, [isReady])
return (
<div className={styles.container}>
<p>q: {q}</p>
<p>asPath: {currentPath}</p>
</div>
)
}
Even if you verify with console.log({ isReady, query, asPath }), you can confirm that while isReady is false, query is {}.
3. What happens if you embed query or asPath in a page built with Server?
For pages with getInitialProps, the query string information is available at the time of Pre-rendering, so there is no problem.
const Home: NextPage = () => {
const { isReady, query, asPath } = useRouter()
return (
<div className={styles.container}>
<p>q: {query.q}</p>
<p>asPath: {asPath}</p>
</div>
)
}
// getInitialProps that does nothing
Home.getInitialProps = () => {
return {};
}
If you verify with console.log({ isReady, query, asPath }), you can confirm that isReady is true from the start.
You should choose which method to use based on the requirements of your server-side processing.
Conclusion
The target audience for this was yesterday's me. Please let me know if there are any errors or inaccuracies.
Discussion