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
- disableCorePrefetching
- onClientEntry
- onInitialClientRender
- onPostPrefetchPathname
- onPreRouteUpdate
- onPrefetchPathname
- onRouteUpdate
- onRouteUpdateDelayed
- onServiceWorkerActive
- onServiceWorkerInstalled
- onServiceWorkerRedundant
- onServiceWorkerUpdateFound
- onServiceWorkerUpdateReady
- registerServiceWorker
- replaceComponentRenderer
- replaceHydrateFunction
- shouldUpdateScroll
- wrapPageElement
- wrapRootElement
Reference
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
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)
// Track pageview with google analytics
window.ga(
`set`,
`page`,
location.pathname + location.search + location.hash,
)
window.ga(`send`, `pageview`)
}
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
replaceComponentRenderer
FunctionSource
(apiCallbackContext: object, pluginOptions: pluginOptions) => ReactNodereplaceComponentRenderer
FunctionAllow a plugin to replace the page component renderer.
Use wrapPageElement to decorate page element.
Parameters
- destructured object
props
objectThe props of the page.
loader
objectThe gatsby loader.
pluginOptions
objectObject 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
_
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.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
FunctionAllow a plugin to decide if the scroll position should update or not on a route change.
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
. 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
FunctionAllow 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.
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
FunctionAllow 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.
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>
)
}