Gatsby Browser APIs
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
wrapPageElementandwrapRootElementexist in both the browser and Server-Side Rendering (SSR) APIs. If you use one of them, consider if you should implement it in bothgatsby-ssr.jsandgatsby-browser.jsso that pages generated through SSR with Node.js are the same after being hydrated with browser JavaScript.
APIs
disableCorePrefetching Function
(_: emptyArg, pluginOptions: pluginOptions) => booleandisableCorePrefetching FunctionPlugins 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 - pluginOptionsis always second argument.
- pluginOptionsobject- Object containing options defined in - gatsby-config.js
Return value
 boolean
Should disable core prefetching
Example
exports.disableCorePrefetching = () => trueonClientEntry Function
(_: emptyArg, pluginOptions: pluginOptions) => undefinedonClientEntry FunctionCalled when the Gatsby browser runtime first starts.
Parameters
- _undefined- This argument is empty. This is for consistency so - pluginOptionsis always second argument.
- pluginOptionsobject- Object containing options defined in - gatsby-config.js
Example
exports.onClientEntry = () => {
  console.log("We've started!")
  callAnalyticsAPI()
}onInitialClientRender Function
(_: emptyArg, pluginOptions: pluginOptions) => undefinedonInitialClientRender FunctionCalled 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 - pluginOptionsis always second argument.
- pluginOptionsobject- Object containing options defined in - gatsby-config.js
Example
exports.onInitialClientRender = () => {
  console.log("ReactDOM.render has executed")
}onPostPrefetchPathname Function
(apiCallbackContext: object, pluginOptions: pluginOptions) => undefinedonPostPrefetchPathname FunctionCalled when prefetching for a pathname is successful. Allows for plugins with custom prefetching logic.
Parameters
- destructured object- pathnamestring- The pathname whose resources have now been prefetched 
 
- pluginOptionsobject- Object containing options defined in - gatsby-config.js
onPreRouteUpdate FunctionSource
(apiCallbackContext: object, pluginOptions: pluginOptions) => undefinedonPreRouteUpdate FunctionCalled when changing location is started.
Parameters
- destructured object- locationobject- A location object 
- prevLocationobject | null- The previous location object 
 
- pluginOptionsobject- 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)
}onPrefetchPathname Function
(apiCallbackContext: object, pluginOptions: pluginOptions) => undefinedonPrefetchPathname FunctionCalled when prefetching for a pathname is triggered. Allows for plugins with custom prefetching logic.
Parameters
- destructured object- pathnamestring- The pathname whose resources should now be prefetched 
- loadPagefunction- Function for fetching resources related to pathname 
 
- pluginOptionsobject- Object containing options defined in - gatsby-config.js
onRouteUpdate FunctionSource
(apiCallbackContext: object, pluginOptions: pluginOptions) => undefinedonRouteUpdate FunctionCalled when the user changes routes, including on the initial load of the app
Parameters
- destructured object- locationobject- A location object 
- prevLocationobject | null- The previous location object 
 
- pluginOptionsobject- 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)
}onRouteUpdateDelayed FunctionSource
(apiCallbackContext: object, pluginOptions: pluginOptions) => undefinedonRouteUpdateDelayed FunctionCalled when changing location is longer than 1 second.
Parameters
- destructured object- locationobject- A location object 
- actionobject- The “action” that caused the route change 
 
- pluginOptionsobject- Object containing options defined in - gatsby-config.js
Example
exports.onRouteUpdateDelayed = () => {
  console.log("We can show loading indicator now")
}onServiceWorkerActive FunctionSource
(apiCallbackContext: object, pluginOptions: pluginOptions) => undefinedonServiceWorkerActive FunctionInform plugins when a service worker has become active.
Parameters
- destructured object- serviceWorkerobject- The service worker instance. 
 
- pluginOptionsobject- Object containing options defined in - gatsby-config.js
onServiceWorkerInstalled FunctionSource
(apiCallbackContext: object, pluginOptions: pluginOptions) => undefinedonServiceWorkerInstalled FunctionInform plugins when a service worker has been installed.
Parameters
- destructured object- serviceWorkerobject- The service worker instance. 
 
- pluginOptionsobject- Object containing options defined in - gatsby-config.js
onServiceWorkerRedundant FunctionSource
(apiCallbackContext: object, pluginOptions: pluginOptions) => undefinedonServiceWorkerRedundant FunctionInform plugins when a service worker is redundant.
Parameters
- destructured object- serviceWorkerobject- The service worker instance. 
 
- pluginOptionsobject- Object containing options defined in - gatsby-config.js
onServiceWorkerUpdateFound FunctionSource
(apiCallbackContext: object, pluginOptions: pluginOptions) => undefinedonServiceWorkerUpdateFound FunctionInform plugins of when a service worker has an update available.
Parameters
- destructured object- serviceWorkerobject- The service worker instance. 
 
- pluginOptionsobject- Object containing options defined in - gatsby-config.js
onServiceWorkerUpdateReady FunctionSource
(apiCallbackContext: object, pluginOptions: pluginOptions) => undefinedonServiceWorkerUpdateReady FunctionInform plugins when a service worker has been updated in the background and the page is ready to reload to apply changes.
Parameters
- destructured object- serviceWorkerobject- The service worker instance. 
 
- pluginOptionsobject- Object containing options defined in - gatsby-config.js
registerServiceWorker FunctionSource
(_: emptyArg, pluginOptions: pluginOptions) => booleanregisterServiceWorker FunctionAllow 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 - pluginOptionsis always second argument.
- pluginOptionsobject- Object containing options defined in - gatsby-config.js
Return value
 boolean
Should Gatsby register /sw.js service worker
Example
exports.registerServiceWorker = () => truereplaceComponentRenderer FunctionSource
(apiCallbackContext: object, pluginOptions: pluginOptions) => ReactNodereplaceComponentRenderer FunctionAllow a plugin to replace the page component renderer.
Use wrapPageElement to decorate page element.
Parameters
- destructured object- propsobject- The props of the page. 
- loaderobject- The gatsby loader. 
 
- pluginOptionsobject- Object containing options defined in - gatsby-config.js
Return value
 ReactNode
Replaced default page renderer
replaceHydrateFunction Function
(_: emptyArg, pluginOptions: pluginOptions) => FunctionreplaceHydrateFunction FunctionAllow 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 - pluginOptionsis always second argument.
- pluginOptionsobject- 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);
  };
};shouldUpdateScroll FunctionSource
(apiCallbackContext: object, pluginOptions: pluginOptions) => boolean | string | ArrayshouldUpdateScroll FunctionAllows 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- prevRouterPropsobject- The previous state of the router before the route change. 
- routerPropsobject- The current state of the router. 
- pathnamestring- The new pathname (for backwards compatibility with v1). 
- getSavedScrollPositionfunction- 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.
 
- pluginOptionsobject- 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
}wrapPageElement FunctionSource
(apiCallbackContext: object, pluginOptions: pluginOptions) => ReactNodewrapPageElement FunctionAllow 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- elementReactNode- The “Page” React Element built by Gatsby. 
- propsobject- Props object used by page. 
 
- pluginOptionsobject- 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>
}wrapRootElement Function
(apiCallbackContext: object, pluginOptions: pluginOptions) => ReactNodewrapRootElement FunctionAllow 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- elementReactNode- The “Root” React Element built by Gatsby. 
 
- pluginOptionsobject- 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>
  )
}