Gatsby vs Next, Comparing Kings of the JAMstack world

Gatsby vs Next, Comparing Kings of the JAMstack world

Server-side rendering (SSR) for React gave birth to many great features, possibilities, and tools like Gatsby and Next.

Introduction

Gatsby and Next, both are the most trending React-based web frameworks. React has grown better faster, it’s not only used for just front-end web development anymore. Now it’s commonly used to develop:

  • SPA (Single Page Apps)
  • Simple browser-based games
  • VR apps with React 360
  • Desktop Apps using Electron.js
  • Mobile apps using React-Native

React's expansiveness has developed outside the web, and it’s inside it has developed too. There are innumerable Frameworks/libraries made on top of React to improve the DX (developer experience) and speed of development. Presently the entire community and activities around React are affectionately known as the React ecosystem. Today, we will look at two of the most well-known React frameworks: Gatsby and Next.

Gatsby & Next - An Introduction

Before we dive into the argument of Next vs Gatsby, we shall take a brief look at what exactly is Gatsby and Next.

What is Gatsby?

Gatsby is an open-source static website generator (SSG) that is based on the frontend development framework React. It makes use of Webpack and GraphQL technology. It can be used to build static sites that are progressive web apps (PWA), follow the latest web standards, and are optimized for speed and security.

The key feature of the framework is built-in performance and it creates static build make the website faster. That’s the reason why Gatsby is at the top of most trending frameworks.

What is Next?

Next is another trending React-based framework. It’s a tool used to build server-side rendering and generating static websites for React-based web applications. Performance isn’t the most key feature for Next.js rather, it's an improved developer experience and reduced hassle to make full-fledged SSR-friendly web applications. Next can build static websites too but it’s not the main focus.

Understanding SSR & SSG

Server-side rendering (SSR) and Static Site Generation (SSG) are the most popular ways to build websites using modern JAMStack while preserving SEO friendliness & better performance.

Server-Side Rendering (SSR)

Have you heard about SPA (Single Page Application)? A single-page application is an application that is rendered at the client-side with fetched data from the server. Server-side rendering (SSR) is the exact opposite of SPA. SSR tells the process of pre-rendering the page on the server-side and then generated upon each user request.

When that page reached the browser, JavaScript code is run to make your page More attractive. So do you know, this big process is loads faster and it also makes SEO a readable website. How does next.js work and what is the technique between this?

Already know that JavaScript became so mature & powerful language, developers usually return static HTML files based on HTTP requests. It was a very common thing to process the response on the server-side using a server-side language like PHP, and returning static HTML files and others.

Static Site Generation (SSG)

SSG is not just a new thing for developers, We already doing that with the beginning of the development of websites. Building rich web experiences can be very hard, but next.js can do easily

Also known as SSG describes the process of building a web that renders at build-time. And the outputs are HTML files & other assets like JavaScript and CSS etc. When you are using Next.js page is pre-rendered at build-time. That means the user does not need to wait for the page to load at the browser. The page will Simply be rendered more fastly.

Usage of SSG and SSR in Next.js

When we describe the usage of this SSG & SSR in Next.js, we can use both techniques in your website that your website makes better rich experiences. What to do is, when we fetching data to the website, we have simple methods for SSG and SSR, let’s find it out.

Data fetching with SSG:

getStaticProps: The web page will be pre-rendered at build time

// pages/posts/index.js
// posts will be populated at build time by getStaticProps()
function Blog({ posts }) {
  return (
    <>
      <ul>
        {posts.map(post => {
          return <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. See the "Technical details" section.
export async function getStaticProps() {
  // 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,
    },
  }
}

export default Blog

getStaticPaths: If your website has dynamic routes and using getStaticProps it needs to define a list of paths that have to be rendered to HTML at Build time.

// pages/posts/[id].js

function Post({ post }) {
  // Render post...
}

// This function gets called at build time
export async function getStaticPaths() {
  // Call an external API endpoint to get posts
  const res = await fetch("https://.../posts")
  const posts = await res.json()

  // Get the paths we want to pre-render based on posts
  const paths = posts.map(post => ({
    params: { id: post.id },
  }))

  // We'll pre-render only these paths at build time.
  // { fallback: false } means other routes should 404.
  return { paths, fallback: false }
}

// This also gets called at build time
export async function getStaticProps({ params }) {
  // params contains the post `id`.
  // If the route is like /posts/1, then params.id is 1
  const res = await fetch(`https://.../posts/${params.id}`)
  const post = await res.json()

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

export default Post

Data fetching with SSR:

getServerSideProps: from a page, Next.js will pre-render this page on each request using the data returned by getServerSideProps.

function Page({ data }) {
  // Render data...
}

// This gets called on every request
export async function getServerSideProps() {
  // 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 } }
}

export default Page

Usage SSG in Gatsby.js

We already said that gatsby is a static site generator, only it can be doing make static sites. That’s the main difference between next and gatsby. So there are many features in gatsby that are not in Next. So we talk about features later. Then we described recently how next uses SSR and SSG, in this case, we’re trying to understand how gatsby uses SSG.

  • Use GraphiQL to query data in the data layer and build your own GraphQL queries.
  • Use useStaticQuery hook to pull data into a “building-block” component.
import * as React from 'react'
import { Link, useStaticQuery, graphql } from 'gatsby'
import {
  container,
  heading,
  navLinks,
  navLinkItem,
  navLinkText
} from './layout.module.css';

const Layout = ({ pageTitle, children }) => {
  const data = useStaticQuery(graphql`
    query {
      site {
        siteMetadata {
          title
        }
      }
    }
  `)
  return (
    // ..render
  )
}
export default Layout
  • Use the gatsby-source-filesystem plugin to pull data into your site from your computer’s filesystem.

Now we understand some core features about data fetching with next and querying data in gatsby. So you better have to get more good experience while you’re developing in both frameworks.

I think you get an idea about the main difference between Nextjs and Gatsbyjs. So Let’s find some other main differences between these frameworks. Let’s look at this image below.

comparing advantages of gatsby and nextjs

I hope you get a better idea about what is in the image. And You need to know about what we gonna do when we’re deploying a site with a build with these frameworks.

Next requires a server for its functioning for SSR feature but Gatsby can run even in the absence of a server.

Conclusion

Next and Gasby are the most famous frameworks and those gave us better developer experience about web development.

While Gatsby is the most ideal choice for building static websites and Next presence for the most logical option for server-side dynamic website