Next.js - Pre-Rendering
- Pre-rendering in Next.js refers to the process of generating HTML pages in advance, before serving them to the client.
 - Next.js supports two types of pre-rendering: Static Generation and Server-side Rendering.
 
1. Static Generation
Static Generation (SG) is the recommended pre-rendering method for Next.js. It generates HTML pages at build time and reuses them on each request.
- To enable Static Generation, create a page in the 
pagesdirectory and export a function calledgetStaticProps. This function fetches data required for the page. - Next.js will pre-render the page with the fetched data and optimize it for performance.
 
2. Server-side Rendering
Server-side Rendering (SSR) generates HTML pages on each request. It's useful for pages that need to be updated frequently or require data that can't be pre-fetched at build time.
- To enable Server-side Rendering, create a page in the 
pagesdirectory and export a function calledgetServerSideProps. This function fetches data required for the page on each request. - Next.js will render the page server-side with the fetched data and send it to the client.
 
3. Example
Here's an example of how to use Static Generation and Server-side Rendering in a Next.js project:
Create a page called posts.js in the pages directory:
import { getStaticProps, getServerSideProps } from 'next';
export async function getStaticProps() {
    // Fetch data for Static Generation
    return {
        props: {
            posts: [/* Data fetched from an API */]
        }
    };
}
export async function getServerSideProps() {
    // Fetch data for Server-side Rendering
    return {
        props: {
            posts: [/* Data fetched from an API */]
        }
    };
}
export default function Posts({ posts }) {
    return (
        
            {/* Render posts */}
        
    );
}
Conclusion
Pre-rendering in Next.js is a powerful feature that improves performance and SEO by generating HTML pages in advance. Whether you choose Static Generation or Server-side Rendering depends on your project requirements, but both methods offer benefits for creating fast and dynamic web applications.
Comments
Post a Comment