When to use server-side rendering (SSR) and static site generation (SSG)?
Tags: typescript, beginners, nextjs, react
Published: 2022-04-22 15:21:56

## Introduction

Hey, here we are to show you the difference and how to apply and hopefully make it easier to learn when to use this two types to displaying your application.

The following infos and codes will be in typescript format and made acoording to NextJs docs to make it easier to understand.

Why not all the API’s calls can be made by `useEffect` and `axios`?! While reading this post you will learn that with the following functions the requests for the API’s will be made out of the clients range, making your data less vulnerable, on the contrary with `useEffect` and `axios` in client side it’s possible, with enough kwnoledge, to access informations by the browser that shouldn’t be able for.

So continue reading to learn a little bit about when to use each of them, and if you need more info about how to use the functions mentioned access the NextJs docs [here.](https://nextjs.org/docs/)

## Server-side Rendering (SSR)

This is a way to an application construct the page on server before be sended to the client’s browser.

When we read the documentation from next to work with SSR we can use the function getServerSideProps,  this function is called only in specific moments, and the most important this function is called in a server-side direct in a node server created by next framework. 

When your fetching is done out of the client(browser) and is executed in a side server where the browser only access the return props from then, that is the reason to your project become more safe

You will use this function when you need to pre-render the fectched data at a request time, every function of your application will do all these fetching before the final render of your application, so use only when needed, if your data doesn’t need a extra layer of protection or if it needed to be updated frequently fetch this data in client side.

The syntax to use getServerSideProps to fetch some data is the following:

```jsx
export default function Page({ data }) {
  // Render data...
}

// This gets called on every request
export const getServerSideProps: GetServerSideProps = async () => {
  // Fetch data from external API
  const res = await fetch(`https://.../data`)
  const data = await res.json()

  // Pass data to the page via props
  return { props: { data } }
}
```

## Static Site Generation (SSG)

This method generate a static HTML site in build time, that is, all the elements fetched or constructed on the function used to do the SSG will be loaded at the moment of project build.

In NextJs we can use the function getStaticProps, that function will return props to your component when you build your project, so do not use this to fetch data that is updated often.

You should use this function when the data required to render the page is avaible in build time, or when it comes from a headless CMS, or the data can be publicly in cache and when the page must be pre-rendered fast for SEO reasons.

The syntax used in getStaticProps is the following:

```jsx
// posts will be populated at build time by getStaticProps()
export default function Blog({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li>{post.title}</li>
      ))}
    </ul>
  )
}

// This function gets called at build time on server-side.
// It won't be called on client-side, so you can even do direct database queries.
export const getStaticProps: GetStaticProps = async () => {
  // Call an external API endpoint to get posts.
  // You can use any data fetching library
  const res = await fetch('https://.../posts')
  const posts = await res.json()

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  }
}

```

## Middleware

The middlewares are functions that intercepts the request and can do some changes before pass the information to another middleware or final component.

This function can be used in NextJs easy peasy, reading the docs we reach this example:

```jsx
// pages/_middleware.ts

import type { NextFetchEvent, NextRequest } from 'next/server'

export function middleware(req: NextRequest, ev: NextFetchEvent) {
  return new Response('Hello, world!')
}
```

In the directory of pages we create a file named `_middleware.ts or .js` and it is setted to use, then this function will intercept the request made by the client and return something based on your rules created.

## Conclusion

When you need to access the payment API is recommended to use one of those functions, in my case i needed to use to retrieve the value of the product to show on the static page, because this doesn’t change frquently i used SSG.

Another example but for SSR is when i had the need to access the information of the posts from an CMS, because they are not often change but need to update when requested, so every time the posts update i can call a revalidate and refetch all data for the posts.

The project that i used this functios is avaible [here.](https://github.com/iagob28/ignews)

Thak you for reaching the end, and a i hope that helped you!