Node API Helpers
The first argument passed to each ofGatsby’s Node APIs is an object containing a set of helpers. Helpers shared by all Gatsby’s Node APIs are documented inShared helpers section.
Common convention is to destructure helpers right in argument list:
TheCreating a Source Plugin tutorial explains some of theShared helpers in more detail.
Note
Some APIs provide additional helpers. For examplecreatePages providesgraphql function. Check documentation of specific APIs inGatsby Node APIs for details.
Shared helpers
Fields
get(key:string)=>Promise<any>Retrieve cached value
Parameters
keystringCache key
Return value
Promise<any>Promise resolving to cached value
Example
const value=await cache.get(`unique-key`)set(key:string,value:any)=>Promise<any>Cache value
Parameters
keystringCache key
valueanyValue to be cached
Return value
Promise<any>Promise resolving to cached value
Example
await cache.set(`unique-key`, value)del(key:string)=>Promise<void>Deletes cached value
Parameters
keystringCache key
Return value
Promise<void>Promise resolving once key is deleted from cache
Example
await cache.del(`unique-key`)
Fields
info(message:string)=>voidParameters
messagestringMessage to display
Return value
voidExample
reporter.info(`text`)warn(message:string)=>voidParameters
messagestringMessage to display
Return value
voidExample
reporter.warn(`text`)error(message:string,error?:Error)=>voidParameters
messagestringMessage to display
errorErrorOptional error object
Return value
voidExample
reporter.error(`text`,newError('something'))panic(message:string,error?:Error)=>voidParameters
messagestringMessage to display
errorErrorOptional error object
Return value
voidExample
reporter.panic(`text`,newError('something'))panicOnBuild(message:string,error?:Error)=>voidParameters
messagestringMessage to display
errorErrorOptional error object
Return value
voidExample
reporter.panicOnBuild(`text`,newError('something'))verbose(message:string)=>voidNote that this method only works if the —verbose option hasbeen passed to the CLI
Parameters
messagestringMessage to display
Return value
voidExample
reporter.verbose(`text`)activityTimer(message:string)=>ITimerReporterCreates a new activity timer with the provided message.Check the fullreturn type definition here.
Parameters
messagestringTimer message to display
Return value
ITimerReporterExample
const activity= reporter.activityTimer(`Timer text`)activity.start()activity.setStatus(`status text`)activity.end()
Fields
tracerOpentracing.TracerGlobal tracer instance. Checkopentracing Tracer documentationfor more details.
parentSpanOpentracing.SpanTracer span representing API run. Checkopentracing Span documentationfor more details.
startSpan(spanName:string)=>Opentracing.SpanStart a tracing span. The span will be created as a child of the currentlyrunning API span. This is a convenience wrapper for
tracing.tracer.startSpan(`span-name`, { childOf: tracing.parentSpan}).Parameters
spanNamestringname of the span
Return value
Opentracing.SpanExample
exports.sourceNodes=async({ actions, tracing})=>{const span= tracing.startSpan(`foo`)// Perform any span operations. E.g. add a tag to your span span.setTag(`bar`,`baz`)// Rest of your plugin code span.finish()}
basePathstring
basePathstringThis is the same aspathPrefix passed ingatsby-config.js.It’s an empty string if you don’t passpathPrefix.When using assetPrefix, you can use this instead of pathPrefix to recieve the string you set ingatsby-config.js.It won’t include theassetPrefix.
cacheGatsbyCache
cacheGatsbyCacheKey-value store used to persist results of time/memory/cpu intensivetasks. All functions are async and return promises.
Fields
get(key:string)=>Promise<any>Retrieve cached value
Parameters
keystringCache key
Return value
Promise<any>Promise resolving to cached value
Example
const value=await cache.get(`unique-key`)set(key:string,value:any)=>Promise<any>Cache value
Parameters
keystringCache key
valueanyValue to be cached
Return value
Promise<any>Promise resolving to cached value
Example
await cache.set(`unique-key`, value)del(key:string)=>Promise<void>Deletes cached value
Parameters
keystringCache key
Return value
Promise<void>Promise resolving once key is deleted from cache
Example
await cache.del(`unique-key`)
createContentDigestFunction
(input:string |object)=>stringcreateContentDigestFunctionCreate a stable content digest from a string or object, you can use theresult of this function to set theinternal.contentDigest fieldon nodes. Gatsby uses the value of this field to invalidate stale datawhen your content changes.
Parameters
inputstring |object
Return value
string
Hash string
Example
const node={...nodeData,internal:{type:`TypeOfNode`,contentDigest:createContentDigest(nodeData)}}createNodeIdFunction
(input:string)=>stringcreateNodeIdFunctionUtility function useful to generate globally unique and stable node IDs.It will generate different IDs for different plugins if they use sameinput.
Parameters
inputstring
Return value
string
UUIDv5 ID string
Example
const node={id:createNodeId(`${backendData.type}${backendData.id}`),...restOfNodeData}emitterEmitter
emitterEmitterInternal event emitter / listener. Do not use, unless you absolutelymust. Emitter is considered a private API and can change with any version.
getNodeFunction
(ID:string)=>NodegetNodeFunctionGet single node by given ID.Don’t use this in graphql resolvers - seegetNodeAndSavePathDependency.
Parameters
IDstringid of the node.
Return value
Node
Single node instance.
Example
const node=getNode(id)getNodeAndSavePathDependencyFunction
(ID:string,path:string)=>NodegetNodeAndSavePathDependencyFunctionGet single node by given ID and create dependency for given path.This should be used instead ofgetNode in graphql resolvers to enabletracking dependencies for query results. If it’s not used Gatsby willnot rerun query if node changes leading to stale query results. SeePage -> Node Dependency Trackingfor more details.
Parameters
IDstringid of the node.
pathstringof the node.
Return value
Node
Single node instance.
getNodesFunction
()=>Node[]getNodesFunctionGet array of all nodes.
Return value
Node[]
Array of nodes.
Example
const allNodes=getNodes()getNodesByTypeFunction
(Type:string)=>Node[]getNodesByTypeFunctionGet array of nodes of given type.
Parameters
Typestringof nodes
Return value
Node[]
Array of nodes.
Example
const markdownNodes=getNodesByType(`MarkdownRemark`)loadNodeContentFunction
(node:Node)=>Promise<string>loadNodeContentFunctionGet content for a node from the plugin that created it.
Parameters
nodeNode
Return value
Promise<string>
Example
module.exports=asyncfunctiononCreateNode({ node, loadNodeContent, actions, createNodeId}){if(node.internal.mediaType==='text/markdown'){const{ createNode, createParentChildLink}= actionsconst textContent=awaitloadNodeContent(node)// process textContent and create child nodes}}parentSpanOpentracing.Span
parentSpanOpentracing.SpanTracer span representing the passed through span from Gatsby to its plugins.Learn more:opentracing Span documentation
pathPrefixstring
pathPrefixstringUse to prefix resources URLs.pathPrefix will be either empty string orpath that starts with slash and doesn’t end with slash.pathPrefix alsobecomes<assetPrefix>/<pathPrefix> when you pass bothassetPrefix andpathPrefix in yourgatsby-config.js.
SeeAdding a Path Prefixpage for details about path prefixing.
reporterGatsbyReporter
reporterGatsbyReporterSet of utilities to output information to user
Fields
info(message:string)=>voidParameters
messagestringMessage to display
Return value
voidExample
reporter.info(`text`)warn(message:string)=>voidParameters
messagestringMessage to display
Return value
voidExample
reporter.warn(`text`)error(message:string,error?:Error)=>voidParameters
messagestringMessage to display
errorErrorOptional error object
Return value
voidExample
reporter.error(`text`,newError('something'))panic(message:string,error?:Error)=>voidParameters
messagestringMessage to display
errorErrorOptional error object
Return value
voidExample
reporter.panic(`text`,newError('something'))panicOnBuild(message:string,error?:Error)=>voidParameters
messagestringMessage to display
errorErrorOptional error object
Return value
voidExample
reporter.panicOnBuild(`text`,newError('something'))verbose(message:string)=>voidNote that this method only works if the —verbose option hasbeen passed to the CLI
Parameters
messagestringMessage to display
Return value
voidExample
reporter.verbose(`text`)activityTimer(message:string)=>ITimerReporterCreates a new activity timer with the provided message.Check the fullreturn type definition here.
Parameters
messagestringTimer message to display
Return value
ITimerReporterExample
const activity= reporter.activityTimer(`Timer text`)activity.start()activity.setStatus(`status text`)activity.end()
storeRedux.Store
storeRedux.StoreInternal redux state used for application state. Do not use, unless youabsolutely must. Store is considered a private API and can change withany version.
tracingGatsbyTracing
tracingGatsbyTracingSet of utilities that allow adding more detailed tracing for plugins.CheckPerformance tracingpage for more details.
Fields
tracerOpentracing.TracerGlobal tracer instance. Checkopentracing Tracer documentationfor more details.
parentSpanOpentracing.SpanTracer span representing API run. Checkopentracing Span documentationfor more details.
startSpan(spanName:string)=>Opentracing.SpanStart a tracing span. The span will be created as a child of the currentlyrunning API span. This is a convenience wrapper for
tracing.tracer.startSpan(`span-name`, { childOf: tracing.parentSpan}).Parameters
spanNamestringname of the span
Return value
Opentracing.SpanExample
exports.sourceNodes=async({ actions, tracing})=>{const span= tracing.startSpan(`foo`)// Perform any span operations. E.g. add a tag to your span span.setTag(`bar`,`baz`)// Rest of your plugin code span.finish()}