Introduction

The file gatsby-browser.js lets you respond to actions within the browser, and wrap your site in additional components. The Gatsby Browser API gives you many options for interacting with the client-side of Gatsby.

Usage

To use Browser APIs, create a file in the root of your site at gatsby-browser.js. Export each API you want to use from this file.

Note: The APIs wrapPageElement and wrapRootElement exist in both the browser and Server-Side Rendering (SSR) APIs. If you use one of them, consider if you should implement it in both gatsby-ssr.js and gatsby-browser.js so that pages generated through SSR with Node.js are the same after being hydrated with browser JavaScript.

APIs

(_: emptyArg, pluginOptions: pluginOptions) => boolean

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

Parameters

  • _ undefined

    This argument is empty. This is for consistency so pluginOptions is always second argument.

  • pluginOptions object

    Object containing options defined in gatsby-config.js

Return value

boolean

Should disable core prefetching

Example

exports.disableCorePrefetching = () => true

onClientEntry Function
Source

(_: emptyArg, pluginOptions: pluginOptions) => undefined

Called when the Gatsby browser runtime first starts.

Parameters

  • _ undefined

    This argument is empty. This is for consistency so pluginOptions is always second argument.

  • pluginOptions object

    Object containing options defined in gatsby-config.js

Example

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

Source

(_: emptyArg, pluginOptions: pluginOptions) => undefined

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

Parameters

  • _ undefined

    This argument is empty. This is for consistency so pluginOptions is always second argument.

  • pluginOptions object

    Object containing options defined in gatsby-config.js

Example

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

(apiCallbackContext: object, pluginOptions: pluginOptions) => undefined

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

  • pluginOptions object

    Object containing options defined in gatsby-config.js


Source

(apiCallbackContext: object, pluginOptions: pluginOptions) => undefined

Called when changing location is started.

Parameters

  • destructured object
    • location object

      A location object

    • prevLocation object | null

      The previous location object

  • pluginOptions object

    Object containing options defined in gatsby-config.js

Example

exports.onPreRouteUpdate = ({ location, prevLocation }) => {
  console.log("Gatsby started to change location to", location.pathname)
  console.log("Gatsby started to change location from", prevLocation ? prevLocation.pathname : null)
}

(apiCallbackContext: object, pluginOptions: pluginOptions) => undefined

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

    • loadPage function

      Function for fetching resources related to pathname

  • pluginOptions object

    Object containing options defined in gatsby-config.js


onRouteUpdate Function
Source

(apiCallbackContext: object, pluginOptions: pluginOptions) => undefined

Called when the user changes routes, including on the initial load of the app

Parameters

  • destructured object
    • location object

      A location object

    • prevLocation object | null

      The previous location object

  • pluginOptions object

    Object containing options defined in gatsby-config.js

Example

exports.onRouteUpdate = ({ location, prevLocation }) => {
  console.log('new pathname', location.pathname)
  console.log('old pathname', prevLocation ? prevLocation.pathname : null)
}

Source

(apiCallbackContext: object, pluginOptions: pluginOptions) => undefined

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

  • pluginOptions object

    Object containing options defined in gatsby-config.js

Example

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

Source

(apiCallbackContext: object, pluginOptions: pluginOptions) => undefined

Inform plugins when a service worker has become active.

Parameters

  • destructured object
    • serviceWorker object

      The service worker instance.

  • pluginOptions object

    Object containing options defined in gatsby-config.js


Source

(apiCallbackContext: object, pluginOptions: pluginOptions) => undefined

Inform plugins when a service worker has been installed.

Parameters

  • destructured object
    • serviceWorker object

      The service worker instance.

  • pluginOptions object

    Object containing options defined in gatsby-config.js


Source

(apiCallbackContext: object, pluginOptions: pluginOptions) => undefined

Inform plugins when a service worker is redundant.

Parameters

  • destructured object
    • serviceWorker object

      The service worker instance.

  • pluginOptions object

    Object containing options defined in gatsby-config.js


Source

(apiCallbackContext: object, pluginOptions: pluginOptions) => undefined

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

Parameters

  • destructured object
    • serviceWorker object

      The service worker instance.

  • pluginOptions object

    Object containing options defined in gatsby-config.js


Source

(apiCallbackContext: object, pluginOptions: pluginOptions) => undefined

Inform plugins when a service worker has been updated in the background and the page is ready to reload to apply changes.

Parameters

  • destructured object
    • serviceWorker object

      The service worker instance.

  • pluginOptions object

    Object containing options defined in gatsby-config.js


Source

(_: emptyArg, pluginOptions: pluginOptions) => boolean

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

Parameters

  • _ undefined

    This argument is empty. This is for consistency so pluginOptions is always second argument.

  • pluginOptions object

    Object containing options defined in gatsby-config.js

Return value

boolean

Should Gatsby register /sw.js service worker

Example

exports.registerServiceWorker = () => true

Source

(apiCallbackContext: object, pluginOptions: pluginOptions) => ReactNode

Allow a plugin to replace the page component renderer.

Use wrapPageElement to decorate page element.

Parameters

  • destructured object
    • props object

      The props of the page.

    • loader object

      The gatsby loader.

  • pluginOptions object

    Object containing options defined in gatsby-config.js

Return value

ReactNode

Replaced default page renderer


Source

(_: emptyArg, pluginOptions: pluginOptions) => Function

Allow a plugin to replace the ReactDOM.render/ReactDOM.hydrate function call by a custom renderer.

Parameters

  • _ undefined

    This argument is empty. This is for consistency so pluginOptions is always second argument.

  • pluginOptions object

    Object containing options defined in gatsby-config.js

Return value

Function

This method 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);
  };
};

Source

(apiCallbackContext: object, pluginOptions: pluginOptions) => boolean | string | Array

Allows a plugin to influence scrolling behavior on navigation. Default behavior is persisting last known scrolling positions and scrolling back to them on navigation. Plugins can also override this and return an Array of coordinates or an element name to scroll to.

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.

  • pluginOptions object

    Object containing options defined in gatsby-config.js

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
}

Source

(apiCallbackContext: object, pluginOptions: pluginOptions) => ReactNode

Allow a plugin to wrap the page element.

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

Note: There is an equivalent hook in Gatsby’s SSR API. It is recommended to use both APIs together. For example usage, check out Using i18n.

Parameters

  • destructured object
    • element ReactNode

      The “Page” React Element built by Gatsby.

    • props object

      Props object used by page.

  • pluginOptions object

    Object containing options defined in gatsby-config.js

Return value

ReactNode

Wrapped element

Example

const React = require("react")
const Layout = require("./src/components/layout").default

exports.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>
}

Source

(apiCallbackContext: object, pluginOptions: pluginOptions) => ReactNode

Allow a plugin to wrap the root element.

This is useful to set up any Provider components that will wrap your application. For setting persistent UI elements around pages use wrapPageElement.

Note: There is an equivalent hook in Gatsby’s SSR API. It is recommended to use both APIs together. For example usage, check out Using redux.

Parameters

  • destructured object
    • element ReactNode

      The “Root” React Element built by Gatsby.

  • pluginOptions object

    Object containing options defined in gatsby-config.js

Return value

ReactNode

Wrapped element

Example

const React = require("react")
const { Provider } = require("react-redux")

const createStore = require("./src/state/createStore")
const store = createStore()

exports.wrapRootElement = ({ element }) => {
  return (
    <Provider store={store}>
      {element}
    </Provider>
  )
}