tiagofsanchez

Thinking how to fetch data in nextjs

April 20, 2021 . 6 min read

nextjs

ssg

ssr

Table of contents

✏️edit

I have been working with Gatsby for a while (this digital garden is build whit it) and to some extend I knew the differences between Client Side Rendering and Static Site Generator, however I wanted to better understand those differences from an implementation standpoint, as well as to better understand how to implement Server Side Render as a data fetching mechanism.

This post is about exploring those different mechanisms using Nextjs framework, mostly because I am planning to venture into a new side project (more on that in a future post) where I will need to think about how to solve this.

SSG, SSR and CSR

About 2 years ago, when I started my journey through React world, and web development, I had no idea about this 3 different concepts, their implications when building webapps and their relationship to performance and SEO. I wouldn't say that now I am an expert on all of those, but to some extend I am a little bit more educated about them.

SSR

Server Side Rendering.

Initially, web frameworks had views rendered on the server (way before I started to code). Every time the client would interact with a given app, that interaction would trigger a request to the server that would pulled the data from a database to send the HTML to the client so that it would be rendered on the browser.

This mechanism happens at every interaction.

CSR

Client Side Rendering.

All the rendering happens in the browser independent of the size of your application. The client browser receives and initial HTML document that will be very simple and will request for the .js scripts that will be used to create the app on the client. In a way this will be a 2 speed process.

This cycle will happen once and the user will have a single page application type of experience.

The difference between SSR and CSR

I have found this amazing quote that tries to put everything into perspective

With server-side rendering, whenever you want to see a new web page, you have to go out and get it, this is analogous to you driving over to the super market every time you want to eat. With client-side rendering, you go to the super market once and spend 45 minutes walking around buying a bunch of food for the month. Then, whenever you want to eat, you just open the fridge. — Adam Zerner

Comparing and contrasting both mechanism is not that straightforward. SSR might perform better on the first render, however CSR could have an edge if the user will interact more with your app.

When we think about the CSR dynamics we generally think about impact on SEO over performance. On the other hand, we generally think that with SSR we will have a great SEO by compromising performance.

To a certain extent that is true, however google has been developing smart ways to improve the SEO on CSR app with something that is called Javascript SEO. Having said that, it does take more time to build your SEO.

SSG

Static Site Generation.

This is where frameworks like Gatsby and Next shine by building everything on the server when you build your app before serving the client side. Personally I really like this approach whenever I am building something with a couple of 100 pages as this will be fantastic UX. The downside, however will be the build time for a app with a couple of pages and the fact that it will be challenging to have dynamic content.

What is interesting, a pretty much the reason I wanted to experiment with Nextjs, is that this framework can handle all of the different data fetching mechanisms.

Let's explore a bit more.

Setting up SSG and SSR with fetch on Nextjs

Nextjs way to do SSG is with the getStaticProps method. Nextjs will use this function during the build process to get any data needed to be passed into the page component as props as follows:

ssg.js

jsx
const SSG = ({pageProps}) => {
//pagProps will be rendered here
}
export async function getStaticProps() {
const res = await fetch("http://stapi.co/api/v1/rest/season/search");
const pageProps = await res.json();
return {
props: { pageProps },
};
}
export default SSG

With this set up, Nextjs will behave in the same way as Gatsbyjs.

If we would need to get SSR we could use the same set up and use the getServerSideProps function that Nextjs provides and 💥, just like that you can transform that page to be a SSR page.

ssr.js

jsx
const SSG = ({pageProps}) => {
//pagProps will be rendered here
}
export async function getServerSideProps() {
const res = await fetch("http://stapi.co/api/v1/rest/season/search");
const pageProps = await res.json();
return {
props: { pageProps },
};
}
export default SSG

SSG and SSR with Apollo client on Nextjs

Given that I will build a GraphQL api endpoint for my future project I decided to also explore how could I set this up with Apollo client.

First I needed to set up Apollo Client.

apollo-client.js

js
import { ApolloClient, InMemoryCache } from "@apollo/client";
const client = new ApolloClient({
uri: "http://localhost:3000/api/graphql",
cache: new InMemoryCache(),
});
export default client;

Next, I needed to query the data and pass that into the component page that that I wanted.

ssgapollo.js

jsx
const SsgApollo = ({ data }) => {
//data will be rendered here
}
export async function getStaticProps() {
const { data } = await client.query({
query: gql`
query {
allPosts {
id
title
}
}
`,
});
if (!data) {
return { notFound: true };
}
return { props: { data } };
}
export default SsgApollo;

As you can probably imagine by now we can quickly change this for SSR just by changing the method to getServerSideProps on this page.

CSR with Apollo

More on this latter!

Other useful resources

If you are really interested to learn more about this I would def recommend the following material:


More posts about Code

Learning Advanced React with Wesbos

4 minutes read

Designing and implementing a megamenu in my digital garden

3 minutes read

All you need to know about CSS transitions

2 minutes read

My digital garden as a gatsby theme: gatsby-theme-tfs

3 minutes read

Hacky way to embed a public instagram in react using gatsby

1 minutes read

Comments made easy with utterances on a gatsby project

2 minutes read

Subscribe

No spam! Only good stuff!