Skip to main content

Gatsby Browser APIs

Usage

Implement any of these APIs by exporting them from a file named gatsby-browser.js in the root of your project.


APIs



Reference

disableCorePrefetching

Plugins can take over prefetching logic. If they do, they should call this to disable the now duplicate core prefetching logic.

Example

exports.disableCorePrefetching = () => true

onClientEntry

Called when the Gatsby browser runtime first starts.

Example

exports.onClientEntry = () => {
  console.log("We've started!")
  callAnalyticsAPI()
}

onInitialClientRender

Called when the initial (but not subsequent) render of Gatsby App is done on the client.

Example

exports.onInitialClientRender = () => {
  console.log("ReactDOM.render has executed")
}

onPostPrefetchPathname

Called when prefetching for a pathname is successful. Allows for plugins with custom prefetching logic.

Parameters

destructured object
pathname {string}

The pathname whose resources have now been prefetched

getResourceURLsForPathname {function}

Function for fetching URLs for resources related to the pathname


onPreRouteUpdate

Called when changing location is started.

Parameters

destructured object
location {object}

A location object

action {object}

The “action” that caused the route change

Example

exports.onPreRouteUpdate = ({ location }) => {
  console.log("Gatsby started to change location", location.pathname)
}

onPrefetchPathname

Called when prefetching for a pathname is triggered. Allows for plugins with custom prefetching logic.

Parameters

destructured object
pathname {string}

The pathname whose resources should now be prefetched

getResourcesForPathname {function}

Function for fetching resources related to pathname


onRouteUpdate

Called when the user changes routes

Parameters

destructured object
location {object}

A location object

action {object}

The “action” that caused the route change

Example

exports.onRouteUpdate = ({ location }) => {
  console.log('new pathname', location.pathname)

  // Track pageview with google analytics
  window.ga(
    `set`,
    `page`,
    location.pathname + location.search + location.hash,
  )
  window.ga(`send`, `pageview`)
}

onRouteUpdateDelayed

Called when changing location is longer than 1 second.

Parameters

destructured object
location {object}

A location object

action {object}

The “action” that caused the route change

Example

exports.onRouteUpdateDelayed = () => {
  console.log("We can show loading indicator now")
}

onServiceWorkerActive

Inform plugins when a service worker has become active.

Parameters

destructured object
serviceWorker {object}

The service worker instance.


onServiceWorkerInstalled

Inform plugins when a service worker has been installed.

Parameters

destructured object
serviceWorker {object}

The service worker instance.


onServiceWorkerRedundant

Inform plugins when a service worker is redundant.

Parameters

destructured object
serviceWorker {object}

The service worker instance.


onServiceWorkerUpdateFound

Inform plugins of when a service worker has an update available.

Parameters

destructured object
serviceWorker {object}

The service worker instance.


registerServiceWorker

Allow a plugin to register a Service Worker. Should be a function that returns true.

Example

exports.registerServiceWorker = () => true

replaceComponentRenderer

Allow a plugin to replace the page component renderer. This api runner can be used to implement page transitions. See https://github.com/gatsbyjs/gatsby/tree/master/examples/using-page-transitions for an example of this.

Parameters

destructured object
props {object}

The props of the page.

loader {object}

The gatsby loader.


replaceHydrateFunction

Allow a plugin to replace the ReactDOM.render function call by a custom renderer. This method takes no param and should return a function with same signature as ReactDOM.render() Note it’s very important to call the callback after rendering, otherwise Gatsby will not be able to call onInitialClientRender

Example

exports.replaceHydrateFunction = () => {
  return (element, container, callback) => {
    console.log("rendering!");
    ReactDOM.render(element, container, callback);
  };
};

shouldUpdateScroll

Allow a plugin to decide if the scroll position should update or not on a route change.

Parameters

destructured object
prevRouterProps {object}

The previous state of the router before the route change.

routerProps {object}

The current state of the router.

pathname {string}

The new pathname (for backwards compatibility with v1).

getSavedScrollPosition {function}

Takes a location and returns the coordinates of the last scroll position for that location, or null. Gatsby saves scroll positions for each route in SessionStorage, so they are available after page reload.

Return value

{boolean|string|Array}

Should return either an [x, y] Array of coordinates to scroll to, a string of the id or name of an element to scroll to, false to not update the scroll position, or true for the default behavior.

Example

exports.shouldUpdateScroll = ({
  routerProps: { location },
  getSavedScrollPosition
}) => {
  const currentPosition = getSavedScrollPosition(location)
  const queriedPosition = getSavedScrollPosition({ pathname: `/random` })

  window.scrollTo(...(currentPosition || [0, 0]))

  return false
}

wrapPageElement

Allow a plugin to wrap the page element.

This is useful for setting wrapper component around pages that won’t get unmounted on page change. For setting Provider components use wrapRootElement.

Note: There is equivalent hook in SSR API

Parameters

destructured object
element {object}

The “Page” React Element built by Gatsby.

props {object}

Props object used by page.

Example

import React from "react"
import Layout from "./src/components/Layout"

export const wrapPageElement = ({ element, props }) => {
  // props provide same data to Layout as Page element will get
  // including location, data, etc - you don't need to pass it
  return <Layout {...props}>{element}</Layout>
}

wrapRootElement

Allow a plugin to wrap the root element.

This is useful to setup any Providers component that will wrap your application. For setting persistent UI elements around pages use wrapPageElement.

Note: There is equivalent hook in SSR API

Parameters

destructured object
element {object}

The “Root” React Element built by Gatsby.

Example

import React from "react"
import { Provider } from "react-redux"

import createStore from "./src/state/createStore"
const store = createStore()

export const wrapRootElement = ({ element }) => {
  return (
    <Provider store={store}>
      {element}
    </Provider>
  )
}