Setting Up Automatic Prerendering in Next.js 14 for Faster Deployment
Explain how to use Next.js 14's automatic prerendering features to optimize the application for faster deployment and performance.
// pages/_app.js
import App from 'next/app';
class MyApp extends App {
static async getInitialProps(appContext) {
// calls page's `getInitialProps` and fills `appProps.pageProps`
const appProps = await App.getInitialProps(appContext);
return { ...appProps };
}
}
export default MyApp;
In your pages/_app.js file, override the default App component to manually handle initial props. Keep in mind that this disables Automatic Static Optimization in Next.js for all pages.
// pages/some-static-page.jsx
export async function getStaticProps() {
// Fetch data and return as props
const data = await fetchData();
return { props: { data } };
}
function SomeStaticPage({ data }) {
return <div>{/* render your page using data */}</div>;
}
export default SomeStaticPage;
For a specific page that you know is static and should be prerendered, you can export `getStaticProps`. This function will fetch data at build time and prerender the page to static HTML.
// pages/some-ssg-page.jsx
export async function getStaticProps() {
// Fetch data and return as props
const data = await fetchData();
return { props: { data }, revalidate: 10 }; // revalidate every 10 seconds
}
function SomeSSGPage({ data }) {
return <div>{/* render your page using data */}</div>;
}
export default SomeSSGPage;
For pages where you want to enable Static Site Generation (SSG) with revalidation, you use `getStaticProps` with the `revalidate` key. This tells Next.js to regenerate the page in the background after deployment if there's a request after the specified time has passed (in this case, 10 seconds).
// pages/some-dynamic-page/[id].jsx
export async function getStaticPaths() {
return { paths: [], fallback: 'blocking' };
}
export async function getStaticProps({ params }) {
// Fetch data based on `params.id` and return as props
const data = await fetchData(params.id);
return { props: { data } };
}
function SomeDynamicPage({ data }) {
return <div>{/* render your page using data */}</div>;
}
export default SomeDynamicPage;
When you have dynamic routes and want to pre-render them, you can use `getStaticPaths`. This example tells Next.js to prerender pages with no paths at build time (`paths: []`) and use 'blocking' fallback to serve new paths by rendering them on-demand at request time.