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
wrapPageElementandwrapRootElementexist in both the browser and Server-Side Rendering (SSR) APIs. You generally should implement the same components in bothgatsby-ssr.jsandgatsby-browser.jsso 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
pluginOptionsis always second argument.pluginOptionsobjectObject 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
_undefinedThis argument is empty. This is for consistency so
pluginOptionsis always second argument.pluginOptionsobjectObject 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
pluginOptionsis always second argument.pluginOptionsobjectObject 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
pathnamestringThe pathname whose resources have now been prefetched
pluginOptionsobjectObject containing options defined in
gatsby-config.js
onPreRouteUpdate FunctionSource
(apiCallbackContext: object, pluginOptions: pluginOptions) => undefinedonPreRouteUpdate FunctionCalled when changing location is started.
Parameters
- destructured object
locationobjectA location object
prevLocationobject | nullThe previous location object
pluginOptionsobjectObject 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
pathnamestringThe pathname whose resources should now be prefetched
loadPagefunctionFunction for fetching resources related to pathname
pluginOptionsobjectObject 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
locationobjectA location object
prevLocationobject | nullThe previous location object
pluginOptionsobjectObject 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
locationobjectA location object
actionobjectThe “action” that caused the route change
pluginOptionsobjectObject 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
serviceWorkerobjectThe service worker instance.
pluginOptionsobjectObject 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
serviceWorkerobjectThe service worker instance.
pluginOptionsobjectObject 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
serviceWorkerobjectThe service worker instance.
pluginOptionsobjectObject 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
serviceWorkerobjectThe service worker instance.
pluginOptionsobjectObject 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
serviceWorkerobjectThe service worker instance.
pluginOptionsobjectObject 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
pluginOptionsis always second argument.pluginOptionsobjectObject containing options defined in
gatsby-config.js
Return value
boolean
Should Gatsby register /sw.js service worker
Example
exports.registerServiceWorker = () => truereplaceHydrateFunction 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
pluginOptionsis always second argument.pluginOptionsobjectObject 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
prevRouterPropsobjectThe previous state of the router before the route change.
routerPropsobjectThe current state of the router.
pathnamestringThe new pathname (for backwards compatibility with v1).
getSavedScrollPositionfunctionTakes a location and returns the coordinates of the last scroll position for that location, or
nulldepending on whether a scroll happened or not. Gatsby saves scroll positions for each route inSessionStorage, so they are available after page reload.
pluginOptionsobjectObject 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 context providers, 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
elementReactNodeThe “Page” React Element built by Gatsby.
propsobjectProps object used by page.
pluginOptionsobjectObject 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 context providers 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
elementReactNodeThe “Root” React Element built by Gatsby.
pluginOptionsobjectObject 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>
)
}