CONTACT US
TABLE OF CONTENTS

The Basics You Should Know About Gatsby API Files

gatsbypicturepagepro

GatsbyJS is a PWA (Progressive Web App) generator which is the most powerful framework that loads only the HTML, CSS, data, and JavaScript.

Thanks to that, your site loads as fast as possible. The project created on Gatsby is loaded once and can prefetches data from resources to your pages, while you surfing around the site.

For example, while you hover some link, GatsbyJS will prefetch data for the next page and cache it from the hovered page, which is boosting your website incredibly.

Every time we work on a project which is based on GatsbyJS we can see 4 files included in the project. These are Gatsby api file.

Let me explain their meaning and the power of them.

Gatsby-config api file

The gatsby-config.js is one of the most important and useful gatsby API files in my opinion.

The config file is important to create global metadata information about the website.

For example:

module.exports = {  
  siteMetadata: {
    title: "Gatsby",
    description: "The fastest website based on gatsby",
    author: "Pagepro"
  }
}

You can add a new plugin to your application. You just need to add the new gatsby plugin into gatsby-config.js file and if you need you can change some option to customize the plugin configuration as you want.

Below is example of some configuration basic plugins which includes popular gatsby plugins like gatsby-plugin-react-helmet which one is important for which lets you control your document head using their React component but also is very important for SEO. If you would like to create styles using styled-components you just need to install them and add it to the plugins. Also as you can see in options you can even set the settings for PWA option as background colour or icon which one may display on the home screen as shortcut on mobile devices.


module.exports = {  
  plugins: [
    "gatsby-plugin-react-helmet",
    "gatsby-plugin-styled-components",
    "gatsby-plugin-sharp",
    {
      resolve: "gatsby-plugin-manifest",
      options: {
        name: "gatsby-starter-default",
        short_name: "starter",
        start_url: "/",
        background_color: "#663399",
        theme_color: "#663399",
        display: "minimal-ui",
        icon: "src/images/gatsby-icon.png"
      }
    }
  }
}

Also, we can use more options :

  • siteMetadata (object)
  • plugins (array)
  • pathPrefix (string)
  • polyfill (boolean)
  • mapping (object)
  • proxy (object)
  • developMiddleware (function)

Gatsby-node api file

The second one is gatsby-node.js

The node file will execute the instructions before the application will be built. This utility makes gatsby so powerful. Before building the application we can create a query which one will fetch the data from any source we want for example we can get data from external API or from GraphQL query. When we get resources data we can use one function called
createPages to create static pages with data from an external source.

In our case we will create pages with prefetched data from our markdown sources and we use to it GraphQL query to create news with special news template.

exports.createPages = async ({ actions, graphql, reporter }) => {
  const { createPage } = actions
  const newsTemplate = path.resolve('src/templates/news.js')

  const result = await graphql(`
    {
      allMarkdownRemark(
        sort: { order: DESC, fields: [frontmatter___date] }
        limit: 1000
      ) {
        edges {
          node {
            id
            frontmatter {
              path
            }
          }
        }
      }
    }
  `)

  if (result.errors) {
    reporter.panicOnBuild(`Error while running GraphQL query.`)
    return
  }

  const posts = result.data.allMarkdownRemark.edges

  posts.forEach(({ node, previous, next }) => {
    createPage({
      path: `news/${node.frontmatter.path}`,
      component: newsTemplate,
      context: {
        originalPath: node.frontmatter.path,
        prev: previous,
        next
      }
    })
  })
}

We can do some executives, while Gatsby will create pages.

Therefore, we can do something before building the application.

Below is the list with available functions you may use in gatsby-node.js

  • createPages
  • createPagesStatefully
  • createResolvers
  • createSchemaCustomization
  • generateSideEffects
  • onCreateBabelConfig
  • onCreateDevServer
  • onCreateNode
  • onCreatePage
  • onCreateWebpackConfig
  • onPostBootstrap
  • onPostBuild
  • onPreBootstrap
  • onPreBuild
  • onPreExtractQueries
  • onPreInit
  • preprocessSource
  • resolvableExtensions
  • setFieldsOnGraphQLNodeType
  • sourceNodes

Gatsby-browser api file

The third one is gatsby-browser.js

The gatsby-browser.js gives you control over Gatsby’s behaviour in the browser. You can trigger some function if user changes routes. Even more, you can call a function when the user first opens any page. For example, while client-side is rendering you can wrap all page in special react component by using wrapPageElement or wrapRootElement. Also, you can do some executives while the client open the page by onClientEntry or give an order to service workers.

Below is the list with available functions you may use in gatsby-browser.js:

  • disableCorePrefetching
  • onClientEntry
  • onInitialClientRender
  • onPostPrefetchPathname
  • onPreRouteUpdate
  • onPrefetchPathname
  • onRouteUpdate
  • onRouteUpdateDelayed
  • onServiceWorkerActive
  • onServiceWorkerInstalled
  • onServiceWorkerRedundant
  • onServiceWorkerUpdateFound
  • onServiceWorkerUpdateReady
  • registerServiceWorker
  • replaceComponentRenderer
  • replaceHydrateFunction
  • shouldUpdateScroll
  • wrapPageElement
  • wrapRootElement

Gatsby-ssr api file

The last one is gatsby-ssr.js.

Gatsby server is rendering while building HTML. You can replace some head elements to be rendered in your index.js. This is very useful when you need to change the order of scripts or styles added by other plugins. Otherwise, Gatsby ssr is very useful when you want to integrate Redux, css-in-js libraries, etc. and when you need to custom setups for server rendering.

Below is the list with available functions you may use in gatsby-ssr.js:

  • onPreRenderHTML
  • onRenderBody
  • replaceRenderer
  • wrapPageElement
  • wrapRootElement
Marek Jakimiuk

Marek, a Frontend Developer at Pagepro since 2017, brings a unique blend of engineering precision and design passion to his role. Marek is known for his advocacy of user experience (UX). He consistently pushes for designs and functionalities that prioritise the user, making him a valuable asset to any project focused on delivering superior digital experiences.

Article link copied

Close button

comments

  • anonymous

    Posted on

    Thank you so much. I am a newbie in Gatsby and i needed to understand this.

Comments are closed.