# 自动静态优化

Next.js自动确定一个页面是静态的(可以预渲染),如果它没有阻塞数据需求。这个决定是由于页面中没有getServerSidePropsgetInitialProps

This feature allows Next.js to emit hybrid applications that contain both server-rendered and statically generated pages.

Statically generated pages are still reactive: Next.js will hydrate your application client-side to give it full interactivity.

One of the main benefits of this feature is that optimized pages require no server-side computation, and can be instantly streamed to the end-user from multiple CDN locations. The result is an ultra fastloading experience for your users.

# How it works

If getServerSidePropsor getInitialPropsis present in a page, Next.js will switch to render the page on-demand, per-request (meaning Server-Side Rendering ).

If the above is not the case, Next.js will statically optimizeyour page automatically by prerendering the page to static HTML.

During prerendering, the router's queryobject will be empty since we do not have queryinformation to provide during this phase. After hydration, Next.js will trigger an update to your application to provide the route parameters in the queryobject.

**Note:**Parameters added with dynamic routes to a page that's using getStaticProps will always be available inside the queryobject.

next buildwill emit .htmlfiles for statically optimized pages. For example, the result for the page pages/about.jswould be:

.next/server/pages/about.html

And if you add getServerSidePropsto the page, it will then be JavaScript, like so:

.next/server/pages/about.js

# Caveats

  • If you have a custom App with getInitialPropsthen this optimization will be turned off in pages without Static Generation .
  • If you have a custom Document with getInitialPropsbe sure you check if ctx.reqis defined before assuming the page is server-side rendered. ctx.reqwill be undefinedfor pages that are prerendered.
Last Updated: 5/13/2023, 8:55:38 PM