Gatsby Browser APIs
Introduction
The file gatsby-browser.jsx
/gatsby-browser.tsx
lets you respond to Gatsby-specific events within the browser, and wrap your page components in additional global components. The Gatsby Browser API gives you many options for interacting with the client-side of Gatsby.
You can author the file in JavaScript or TypeScript.
Usage
To use Browser APIs, create a file in the root of your site at gatsby-browser.jsx
/gatsby-browser.tsx
. Export each API you want to use from this file.
Note: The APIs
wrapPageElement
andwrapRootElement
exist in both the browser and Server-Side Rendering (SSR) APIs. You generally should implement the same components in bothgatsby-ssr.js
andgatsby-browser.js
so that pages generated through SSR are the same after being hydrated in the browser.
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
_
undefinedThis argument is empty. This is for consistency so
pluginOptions
is always second argument.pluginOptions
objectObject containing options defined in
gatsby-config.js
Return value
boolean
Should disable core prefetching
Example
exports.disableCorePrefetching = () => true
onClientEntry
Function
(_: emptyArg, pluginOptions: pluginOptions) => undefinedonClientEntry
FunctionCalled when the Gatsby browser runtime first starts.
Parameters
_
undefinedThis argument is empty. This is for consistency so
pluginOptions
is always second argument.pluginOptions
objectObject 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
_
undefinedThis argument is empty. This is for consistency so
pluginOptions
is always second argument.pluginOptions
objectObject 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
pathname
stringThe pathname whose resources have now been prefetched
pluginOptions
objectObject containing options defined in
gatsby-config.js
onPreRouteUpdate
FunctionSource
(apiCallbackContext: object, pluginOptions: pluginOptions) => undefinedonPreRouteUpdate
FunctionCalled when changing location is started.
Parameters
- destructured object
location
objectA location object
prevLocation
object | nullThe previous location object
pluginOptions
objectObject 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
pathname
stringThe pathname whose resources should now be prefetched
loadPage
functionFunction for fetching resources related to pathname
pluginOptions
objectObject 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
location
objectA location object
prevLocation
object | nullThe previous location object
pluginOptions
objectObject 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
location
objectA location object
action
objectThe “action” that caused the route change
pluginOptions
objectObject 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
serviceWorker
objectThe service worker instance.
pluginOptions
objectObject 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
serviceWorker
objectThe service worker instance.
pluginOptions
objectObject 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
serviceWorker
objectThe service worker instance.
pluginOptions
objectObject 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
serviceWorker
objectThe service worker instance.
pluginOptions
objectObject 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
serviceWorker
objectThe service worker instance.
pluginOptions
objectObject 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
_
undefinedThis argument is empty. This is for consistency so
pluginOptions
is always second argument.pluginOptions
objectObject containing options defined in
gatsby-config.js
Return value
boolean
Should Gatsby register /sw.js
service worker
Example
exports.registerServiceWorker = () => true
replaceHydrateFunction
Function
(_: emptyArg, pluginOptions: pluginOptions) => FunctionreplaceHydrateFunction
FunctionAllow a plugin to replace the ReactDOM.createRoot
/render
function calls with a custom renderer.
Parameters
_
undefinedThis argument is empty. This is for consistency so
pluginOptions
is always second argument.pluginOptions
objectObject containing options defined in
gatsby-config.js
Return value
Function
This method should return a function with same signature as ReactDOM.createRoot
/render
Note:
Refer to React’s documentation on ReactDOM.createRoot
/render
for more information.
Note that ReactDOM.createRoot
/render
is only available in React 18 or greater, prior versions should use ReactDOM.render
.
Example
exports.replaceHydrateFunction = () => {
return (element, container) => {
const root = ReactDOM.createRoot(container)
root.render(element)
}
}
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
prevRouterProps
objectThe previous state of the router before the route change.
routerProps
objectThe current state of the router.
pathname
stringThe new pathname (for backwards compatibility with v1).
getSavedScrollPosition
functionTakes a location and returns the coordinates of the last scroll position for that location, or
null
depending on whether a scroll happened or not. Gatsby saves scroll positions for each route inSessionStorage
, so they are available after page reload.
pluginOptions
objectObject 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
FunctionCan be used to wrap each 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
ReactNodeThe “Page” React Element built by Gatsby.
props
objectProps object used by page.
pluginOptions
objectObject 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
FunctionCan be used to the 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
ReactNodeThe “Root” React Element built by Gatsby.
pluginOptions
objectObject 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>
)
}