Server-Side Rendering (SSR) VS. Static Site Generation (SSG) In NextJs

blog-banner

Next.js is an open-source framework built on top of React that simplifies building web applications. It adds features and functionalities specifically useful for React developers.

Think of it this way:

  • Regular React is like building a car from scratch.
  • Next.js is like having a pre-built engine, frame/body, and navigation system, letting you focus on the unique features of your car.

Types of rendering in NextJS:

Before that lets understand rendering.

Rendering a web page involves generating and displaying the site so that it appears correctly on your computer or mobile device, allowing for seamless interaction. This process transforms all the code, content, images, and other elements of a website into what you see in your web browser. In Next.js, various rendering methods are employed to determine how a page or component is rendered, whether on the server side or the client side.

In Next.js, multiple rendering strategies are available, each dictating how a page or component is processed and displayed, either on the server side or the client side. These methods are Server-side Rendering (SSR), Client-side Rendering (CSR), Server-side Generation (SSG), and Incremental Static Regeneration (ISR). Let’s explore each of these rendering methods.

Client-side Rendering (CSR):

  • The server sends only the minimal HTML necessary to render the page structure.
  • JavaScript code is then responsible for fetching data and dynamically rendering the content in the browser.

Server-side Rendering (SSR):

  • When a request arrives, the server fetches data and executes your application code to generate the complete HTML response.
  • This pre-rendered HTML includes the content and any initial JavaScript needed.

Static Site Generation (SSG):

  • Pages are pre-rendered at build time.
  • Data is fetched and the entire HTML is generated during the build process.
  • The resulting HTML is then served directly on subsequent requests.

Incremental Static Regeneration (ISR):

  • Similar to SSG, pages are pre-rendered at build time.
  • However, ISR allows you to define a revalidation timeframe.
  • If a request comes in for a page outside the validity window, the server fetches new data and regenerates the HTML before serving it.

Now, let’s dive deep into the difference between Server-side Rendering (SSR) and Static Site Generation (SSG):

Server Side Rendering (SSR):

SSR is like baking cookies every time someone orders them. The server (bakery) prepares the fresh content (cookie) for each customer (request). It's great for pages that need the latest information, but can take a little longer to load.

Implementation of SSR with NextJS:

In Next.js, you can utilize Server-Side Rendering by incorporating the getServerSideProps function.

This function is used in the following example to retrieve data from the server with every user request, ensuring that the content users receive is always up-to-date and dynamically generated.

Step 1:

Create a new next app

npx [email protected] server-side-rendering-app

Navigate to the folder using CMD

cd server-side-rendering-app

Step 2:

Create a ssr directory under page directory and index file as suggested below:

// page/ssr/index.js 

const ssrExample = ({ users }) => (
 <div>
 <h1>Users</h1>
 <ul>
  {users.map((user) => (
	<li key={user.id}>{user.name}</li>
  ))}
 </ul>
 </div>
);
export default ssrExample;
export async function getServerSideProps() {
 const response = await fetch("https://jsonplaceholder.typicode.com/users");
 const data = await response.json();
 return {
	props: {
		users: data,
	}, 
 }; 
}

Note: getStaticProps() is not available in next14.

Step 3:

Run your Next.js applications:

npm run dev 

Step 4:

Navigate to http://localhost:3000/ssr

Pros of SSR:

  • Always Up-to-Date: Perfect for real-time features like chat or social media where content needs to be constantly fresh.
  • Data Powerhouse: Great for fetching and processing data on the server before sending it to the user.

Cons of SSR:

  • Slower Startup: Rendering on the server takes extra time compared to pre-built static pages.
  • Server Strain: High traffic can overwhelm your server, impacting performance.
  • More Complex Setup: Implementing features like user authentication requires additional work.

Static Site Generation (SSG):

SSG is like baking a big batch of cookies in advance. The server (bakery) bakes the cookies (pre-renders the pages) at build time, so they are ready to serve quickly to anyone who comes in (requests the page). This is good for content that doesn't change often.

In Next.js, Static Site Generation can be achieved with the getStaticProps function. During the build process, this function pre-renders the HTML for the page, resulting in a static, fast-loading webpage.

Implementation of SSG with NextJS:

Step 1:

Create new nextJS project, if not created earlier:

npx [email protected] static-site-generation-app 

then move to that directory using CMD

cd static-site-generation-app 

Step 2:

Create a ssg directory under page directory and index file as suggested below:

// page/ssg/index.js 

const ssgExample = ({ users }) => (
 <div>
 <h1>Users</h1>
 <ul>
  {users.map((user) => ( 
   <li key={user.id}>{user.name}</li>
  ))}
 </ul>
 </div>
);
export default ssgExample;
export async function getStaticProps() {
  const response = await fetch("https://jsonplaceholder.typicode.com/users"); 
  const data = await response.json(); 
  return {
   props: { 
	users: data,
   },
  };
}

Note: getStaticProps() is not available in next14.

Step 3:

Run your App

npm run dev 

Step 4:

Navigate to http://localhost:3000/ssg

Pros of SSG:

  • SEO Friendly: Search engines love pre-rendered HTML, boosting your website's ranking.
  • Blazing Fast: Pages load instantly thanks to pre-built content.
  • Scales Like a Champ: Handles high traffic with ease due to reduced server load.

Cons of SSG:

  • Stale Content: Updates require rebuilding the entire site, causing delays.
  • Build Time Blues: Building large websites with many pages can be time-consuming.
  • Authentication Woes: Complex authentication logic might not be ideal for SSG.

Choosing the Right Method:

The optimal choice between SSR and SSG depends on your application's specific needs. Here's a breakdown to help you decide:

  • Prioritize real-time updates and user authentication: Go with SSR for applications like chat rooms, social media platforms, or e-commerce sites where user interaction and secure data handling are crucial.
  • Focus on SEO, performance, and scalability for static content: Choose SSG for websites like blogs, portfolios, documentation, or news sites where content updates are less frequent. SSG excels in these scenarios due to its SEO benefits, fast loading times, and reduced server load.

Remember, Next.js also offers Incremental Static Regeneration (ISR) as a hybrid approach that combines some advantages of both SSR and SSG. Consider ISR for content that requires occasional updates but still benefits from pre-rendered pages.

As a summary, here’s the difference

Server-Side Rendering (SSR) Static Site Generation (SSG)
The server generates a fresh page for each request Pages are pre-generated at build time
Ideal for pages that need the latest information Suited for pages where content doesn't change often
May take longer to load Pages are quickly served to users

Conclusion:

Choosing between Server-Side Rendering (SSR) and Static Site Generation (SSG) in Next.js depends on the specific needs of your application. SSR is ideal for dynamic, real-time content and secure user interactions, making it suitable for applications like e-commerce sites and social media platforms. On the other hand, SSG excels in delivering fast, SEO-friendly static content, making it perfect for blogs, portfolios, and documentation sites. For applications that require a balance, Incremental Static Regeneration (ISR) offers a hybrid approach. Ultimately, understanding your project requirements will guide you to the best rendering strategy. Each approach caters to distinct project requirements, and understanding these differences is essential for JavaScript development services provider leveraging Next.js.

Contact us

For Your Business Requirements

Text to Identify Refresh CAPTCHA
Background Image Close Button

2 - 4 October 2024

Hall: 10, Booth: #B8 Brussels, Belgium