Gatsby Node APIs
Introduction
Gatsby gives plugins and site builders many APIs for building your site. Code in the filegatsby-node.js/gatsby-node.ts is run once in the process of building your site. You can use its APIs to create pages dynamically, add data into GraphQL, or respond to events during the build lifecycle. To use the Gatsby Node APIs, create a file namedgatsby-node.js/gatsby-node.ts in the root of your site. Export any of the APIs you wish to use in this file.
You can author the file in JavaScript (CommonJS orES Modules (ESM) syntax) orTypeScript.
Every Gatsby Node API gets passed aset of helper functions. These let you access several methods like reporting, or perform actions like creating new pages.
An examplegatsby-node.js file that implements two APIs,onPostBuild, andcreatePages.
TheTypeScript and Gatsby documentation shows how to set up agatsby-node file in TypeScript.
Read theES Modules (ESM) and Gatsby documentation if you don’t want to use CommonJS syntax.
Async vs. sync work
If your plugin performs async operations (disk I/O, database access, calling remote APIs, etc.) you must either return a promise (explicitly usingPromise API or implicitly usingasync/await syntax) or use the callback passed to the 3rd argument. Gatsby needs to know when plugins are finished as some APIs, to work correctly, require previous APIs to be complete first. SeeDebugging Async Lifecycles for more info.
If your plugin does not do async work, you can return directly.
APIs
Create pages dynamically. This extension point is called only after the initialsourcing and transformation of nodes plus creation of the GraphQL schema arecomplete so you can query your data in order to create pages.
You can also fetch data from remote or local sources to create pages.
Parameters
- destructured object
graphqlfunction: Query GraphQL API. Seeexamples here
reporterGatsbyReporterLog issues. SeeGatsbyReporter documentation for more details
Return value
Promise<void>
No return value required, but the caller willawait any promise that’s returned
Example
const path=require(`path`)exports.createPages=({ graphql, actions})=>{const{ createPage}= actionsconst blogPostTemplate= path.resolve(`src/templates/blog-post.js`)// Query for markdown nodes to use in creating pages.// You can query for whatever data you want to create pages for e.g.// products, portfolio items, landing pages, etc.// Variables can be added as the second function parameterreturngraphql(` query loadPagesQuery ($limit: Int!) { allMarkdownRemark(limit: $limit) { edges { node { frontmatter { slug } } } } }`,{limit:1000}).then(result=>{if(result.errors){throw result.errors}// Create blog post pages. result.data.allMarkdownRemark.edges.forEach(edge=>{createPage({// Path for this page — requiredpath:`${edge.node.frontmatter.slug}`,component: blogPostTemplate,context:{// Add optional context data to be inserted// as props into the page component.//// The context data can also be used as// arguments to the page GraphQL query.//// The page "path" is always available as a GraphQL// argument.},})})})}LikecreatePages but for plugins who want to manage creating and removingpages themselves in response to changes in datanot managed by Gatsby.Plugins implementingcreatePages will get called regularly to recomputepage information as Gatsby’s data changes but those implementingcreatePagesStatefully will not.
An example of a plugin that uses this extension point is the plugingatsby-plugin-page-creatorwhich monitors thesrc/pages directory for the adding and removal of JSpages. As its source of truth, files in the pages directory, is not known byGatsby, it needs to keep its own state about its world to know when toadd and remove pages.
Source
Add custom field resolvers to the GraphQL schema.
Allows adding new fields to types by providing field configs, or adding resolverfunctions to existing fields.
Things to note:
- Overriding field types is disallowed, instead use the
createTypesaction. In case of types added from third-party schemas, where this is notpossible, overriding field types is allowed. - New fields will not be available on
filterandsortinput types. Extendtypes defined withcreateTypesif you need this. - In field configs, types can be referenced as strings.
- When extending a field with an existing field resolver, the originalresolver function is available from
info.originalResolver. - The
createResolversAPI is called as the last step in schema generation.Thus, an intermediate schema is made available on theintermediateSchemaproperty.In resolver functions themselves, it is recommended to access the finalbuilt schema frominfo.schema. - Gatsby’s data layer, including all internal query capabilities, isexposed on
context.nodeModel. The node store can bequeried directly withfindOne,getNodeByIdandgetNodesByIds,while more advanced queries can be composed withfindAll. - It is possible to add fields to the root
Querytype. - When using the first resolver argument (
sourcein the example below,often also calledparentorroot), take care of the fact that fieldresolvers can be called more than once in a query, e.g. when the field ispresent both in the input filter and in the selection set. This means thatforeign-key fields onsourcecan be either resolved or not-resolved.
For fuller examples, seeusing-type-definitions.
Parameters
- destructured object
intermediateSchemaGraphQLSchemaCurrent GraphQL schema
createResolversfunctionAdd custom resolvers to GraphQL field configs
$1objectresolversobjectAn object map of GraphQL type names to custom resolver functions
optionsobjectOptional createResolvers options
ignoreNonexistentTypesobjectSilences the warning when trying to add resolvers for types that don’t exist. Useful for optional extensions.
Example
exports.createResolvers=({ createResolvers})=>{const resolvers={Author:{fullName:{resolve:(source, args, context, info)=>{return source.firstName+ source.lastName}},},Query:{allRecentPosts:{type:[`BlogPost`],resolve:async(source, args, context, info)=>{const{ entries}=await context.nodeModel.findAll({type:`BlogPost`})return entries.filter(post=> post.publishedAt> Date.UTC(2018,0,1))}}}}createResolvers(resolvers)}Customize Gatsby’s GraphQL schema by creating type definitions, fieldextensions or adding third-party schemas.
ThecreateTypes,createFieldExtension andaddThirdPartySchema actionsare only available in this API. For details on their usage please refer tothe actions documentation.
This API runs immediately before schema generation. For modifications of thegenerated schema, e.g. to customize added third-party types, use thecreateResolvers API.
Parameters
- destructured object
actionsobjectcreateTypesobjectcreateFieldExtensionobjectaddThirdPartySchemaobject
Example
exports.createSchemaCustomization=({ actions})=>{const{ createTypes, createFieldExtension}= actionscreateFieldExtension({name:'shout',extend:()=>({resolve(source, args, context, info){returnString(source[info.fieldName]).toUpperCase()}})})const typeDefs=` type MarkdownRemark implements Node @dontInfer { frontmatter: Frontmatter } type Frontmatter { title: String! tagline: String @shout date: Date @dateformat image: File @fileByRelativePath }`createTypes(typeDefs)}Let plugins extend/mutate the site’s Babel configuration by callingsetBabelPlugin orsetBabelPreset.
Parameters
- destructured object
stagestringThe current build stage. One of ‘develop’, ‘develop-html’,‘build-javascript’, or ‘build-html’
actionsobject
optionsobjectThe Babel configuration
Example
exports.onCreateBabelConfig=({ actions})=>{ actions.setBabelPlugin({name:`babel-plugin-that-i-like`,options:{}})}Run when thegatsby develop server is started. It can be used for adding proxies and Express middlewareto the server.
Parameters
- destructured object
appExpressTheExpress app used to run the dev server
Example
exports.onCreateDevServer=({ app})=>{ app.get('/hello',function(req, res){ res.send('hello world')})}Source
Called when a new node is created. Plugins wishing to extend ortransform nodes created by other plugins should implement this API.
See also the documentation forcreateNodeandcreateNodeField
TheCreating a SourcePlugin tutorialdemonstrates a way a plugin or site might use this API.
Example
exports.onCreateNode=({ node, actions})=>{const{ createNode, createNodeField}= actions// Transform the new node here and create a new node or// create a new node field.}Called when a new page is created. This extension API is usefulfor programmatically manipulating pages created by other plugins e.g.if you want paths without trailing slashes.
There is a mechanism in Gatsby to prevent calling onCreatePage for pagescreated by the same gatsby-node.js to avoid infinite loops/callback.
See the guideCreating and Modifying Pagesfor more on this API.
Source
Let plugins extend/mutate the site’s webpack configuration. This method can be used by any Gatsby site, app, or plugin, not just plugins.
See also the documentation forsetWebpackConfig.
Parameters
- destructured object
stagestringThe current build stage. One of ‘develop’, ‘develop-html’,‘build-javascript’, or ‘build-html’
getConfigfunctionReturns the current webpack config
rulesobjectA set of preconfigured webpack config rules
loadersobjectA set of preconfigured webpack config loaders
pluginsobjectA set of preconfigured webpack config plugins
actionsobject
Example
exports.onCreateWebpackConfig=({ stage, getConfig, rules, loaders, actions})=>{ actions.setWebpackConfig({module:{rules:[{test:'my-css',use:[loaders.style(), loaders.css()]},],},});}Lifecycle executed in each process (one time per process). Used to store actions etc for later use.
Example
let createJobV2exports.onPluginInit=({ actions})=>{// store job creation action to use it later createJobV2= actions.createJobV2}Called at the end of the bootstrap process after all other extension APIs have been called.
The last extension point called after all other parts of the build processare complete.
Example
exports.onPostBuild=({ reporter, basePath, pathPrefix})=>{ reporter.info(`Site was built with basePath:${basePath} & pathPrefix:${pathPrefix}`);};Called once Gatsby has initialized itself and is ready to bootstrap your site.
The first extension point called during the build process. Called after the bootstrap has completed but before the build steps start.
Run before GraphQL queries/fragments are extracted from JavaScript files. Useful for pluginsto add more JavaScript files with queries/fragments e.g. from node_modules.
See gatsby-transformer-sharp and gatsby-source-contentful for examples.
The first API called during Gatsby execution, runs as soon as plugins are loaded, before cache initialization and bootstrap preparation.
Parameters
- destructured object
actionsobject
Example
exports.onPreInit=({ actions})=>{}Run during the bootstrap phase. Plugins can use this to define a schema for their options usingJoi to validate the options users pass to the plugin.
Parameters
- destructured object
JoiJoiThe instance ofJoi to define the schema
Example
exports.pluginOptionsSchema=({ Joi})=>{return Joi.object({// Validate that the anonymize option is defined by the user and is a booleananonymize: Joi.boolean().required(),})}Ask compile-to-js plugins to process source to JavaScript so the queryrunner can extract out GraphQL queries for running.
Lets plugins implementing support for other compile-to-js add to the listof “resolvable” file extensions. Gatsby supports.js and.jsx by default.
Return value
string[]
array of extensions
Source
Called during the creation of the GraphQL schema. Allows pluginsto add new fields to the types created from data nodes. It will be calledseparately for each type.
This function should return an object in the shape ofGraphQLFieldConfigMapwhich will be appended to fields inferred by Gatsby from data nodes.
Note: Import GraphQL types fromgatsby/graphql and don’t add thegraphqlpackage to your project/plugin dependencies to avoidSchema mustcontain unique named types but contains multiple types named errors.gatsby/graphql exports all builtin GraphQL types as well as theGraphQLJSONtype.
Many transformer plugins use this to add fields that take arguments.
adds an “excerpt” field where the user when writing their query can specifyhow many characters to prune the markdown source to.
gatsby-transformer-sharpexposes
many image transformation options as GraphQL fields.
Parameters
- destructured object
typeobjectObject containing
nameandnodes
Example
import{ GraphQLString}from"gatsby/graphql"exports.setFieldsOnGraphQLNodeType=({ type})=>{if(type.name===`File`){return{newField:{type: GraphQLString,args:{myArgument:{type: GraphQLString,}},resolve:(source, fieldArgs)=>{return`Id of this node is${source.id}. Field was called with argument:${fieldArgs.myArgument}`}}}}// by default return empty objectreturn{}}Called before scheduling aonCreateNode callback for a plugin. If it returns falsythen Gatsby will not schedule theonCreateNode callback for this node for this plugin.Note: this API does not receive the regularapi that other callbacks get as first arg.
Example
exports.shouldOnCreateNode=({node}, pluginOptions)=> node.internal.type==='Image'Extension point to tell plugins to source nodes. This API is called duringthe Gatsby bootstrap sequence. Source plugins use this hook to create nodes.This API is called exactly once per plugin (and once for your site’sgatsby-config.js file). If you define this hook ingatsby-node.js itwill be called exactly once after all of your source plugins have finishedcreating nodes.
TheCreating a SourcePlugin tutorialdemonstrates a way a plugin or site might use this API.
See also the documentation forcreateNode.
Example
exports.sourceNodes=({ actions, createNodeId, createContentDigest})=>{const{ createNode}= actions// Data can come from anywhere, but for now create it manuallyconst myData={key:123,foo:`The foo field of my node`,bar:`Baz`}const nodeContent=JSON.stringify(myData)const nodeMeta={id:createNodeId(`my-data-${myData.key}`),parent:null,children:[],internal:{type:`MyNodeType`,mediaType:`text/html`,content: nodeContent,contentDigest:createContentDigest(myData)}}const node= Object.assign({}, myData, nodeMeta)createNode(node)}