Dave Gray

When to Use Static Generation vs. Server-side Rendering

March 17, 2023

We recommend using Static Generation (with and without data) whenever possible because your page can be built once and served by CDN, which makes it much faster than having a server render the page on every request.

You can use Static Generation for many types of pages, including:

  • Marketing pages
  • Blog posts
  • E-commerce product listings
  • Help and documentation

You should ask yourself: "Can I pre-render this page ahead of a user's request?" If the answer is yes, then you should choose Static Generation.

On the other hand, Static Generation is not a good idea if you cannot pre-render a page ahead of a user's request. Maybe your page shows frequently updated data, and the page content changes on every request.

Knowledge of and adherence to best coding standards can aid in demonstrating a developer's skill and professionalism and can be viewed as a crucial aspect of career advancement.

1. Use strict mode

Adding "use strict"; at the beginning of your JavaScript code will enforce strict syntax rules, making it easier to find bugs and potential security issues.

Example:

'use strict';
var x = 5;

2. Declare variables with let and const

In contrast to variables whose value is constant, let is used for variables whose value will vary.

This improves the readability of your code and guards against inadvertent changes to variables.

Example:

let name = "John";
name = "Jane";

const PI = 3.14;

3. Use === and !== instead of == and !=

The === and !== operators perform type checking, whereas == and != perform type coercion. This can lead to unexpected results.

Example:

if (1 === "1") {
  console.log("Equal");
} else {
  console.log("Not equal");
} 
// Output: Not equal

4. Avoid using global variables

Global variables can easily be overwritten or changed, leading to unpredictable behavior in your code. Instead, use modules or closures to create private variables.

Example:

(function () {
  var message = "Hello";
  console.log(message);
})();

5. Write readable and maintainable code

Use meaningful variable names, add comments to explain your code, and write code that is easy to understand for others.

Example:

// Function to calculate the area of a circle function calcCircleArea(radius) {
  return Math.PI * Math.pow(radius, 2);
}

6. Minimize the use of null and undefined:

Instead of checking for null and undefined, consider using default values or || operator to handle missing data.

Example:

let name = "John";
console.log(name || "Guest"); // Output: John

In that case, you can use Server-Side Rendering. It will be slower, but the pre-rendered page will always be up-to-date. Or you can skip pre-rendering and use client-side JavaScript to populate data.

← Back to home