Actions
Gatsby uses Redux internally to manage state. When you implement a Gatsby API, you are passed a collection of actions (equivalent to actions bound with bindActionCreators in Redux) which you can use to manipulate state on your site.
The object actions contains the functions and these can be individually extracted by using ES6 object destructuring.
Functions
Source
Add a third-party schema to be merged into main schema. Schema has to be a graphql-js GraphQLSchema object.
This schema is going to be merged as-is. This can easily break the main Gatsby schema, so it’s user’s responsibility to make sure it doesn’t happen (by e.g. namespacing the schema).
Parameters
- destructured object
schemaGraphQLSchemaGraphQL schema to add
pluginIGatsbyPlugintraceIdstring
Return value
IAddThirdPartySchema
Source
Add a field extension to the GraphQL schema.
Extensions allow defining custom behavior which can be added to fields
via directive (in SDL) or on the extensions prop (with Type Builders).
The extension definition takes a name, an extend function, and optional
extension args for options. The extend function has to return a (partial)
field config, and receives the extension options and the previous field config
as arguments.
Parameters
extensionGraphQLFieldExtensionDefinitionThe field extension definition
pluginIGatsbyPlugintraceIdstring
Return value
ThunkAction<>
Example
exports.createSchemaCustomization = ({ actions }) => {
const { createFieldExtension } = actions
createFieldExtension({
name: 'motivate',
args: {
caffeine: 'Int'
},
extend(options, prevFieldConfig) {
return {
type: 'String',
args: {
sunshine: {
type: 'Int',
defaultValue: 0,
},
},
resolve(source, args, context, info) {
const motivation = (options.caffeine || 0) - args.sunshine
if (motivation > 5) return 'Work! Work! Work!'
return 'Maybe tomorrow.'
},
}
},
})
}Source
Create a “job”. This is a long-running process that is generally
started as a side-effect to a GraphQL query.
gatsby-plugin-sharp uses this for
example.
Gatsby doesn’t finish its process until all jobs are ended.
Parameters
jobObjectA job object with at least an id set
ididThe id of the job
plugin
Example
createJob({ id: `write file id: 123`, fileName: `something.jpeg` })Source
Create a “job”. This is a long-running process that is generally
started as a side-effect to a GraphQL query.
gatsby-plugin-sharp uses this for
example.
Gatsby doesn’t finish its process until all jobs are ended.
Parameters
jobObjectA job object with name, inputPaths, outputDir and args
namestringThe name of the job you want to execute
inputPathsstring[]The inputPaths that are needed to run
outputDirstringThe directory where all files are being saved to
argsObjectThe arguments the job needs to execute
pluginPlugin
Return value
Promise<object>
Promise to see if the job is done executing
Example
createJobV2({ name: `IMAGE_PROCESSING`, inputPaths: [`something.jpeg`], outputDir: `public/static`, args: { width: 100, height: 100 } })Source
Create a new node.
Parameters
nodeObjecta node object
idstringThe node’s ID. Must be globally unique.
parentstringThe ID of the parent’s node. If the node is derived from another node, set that node as the parent. Otherwise it can just be
null.childrenArrayAn array of children node IDs. If you’re creating the children nodes while creating the parent node, add the children node IDs here directly. If you’re adding a child node to a parent node created by a plugin, you can’t mutate this value directly to add your node id, instead use the action creator
createParentChildLink.internalObjectnode fields that aren’t generally interesting to consumers of node data but are very useful for plugin writers and Gatsby core. Only fields described below are allowed in
internalobject. Using any type of custom fields will result in validation errors.mediaTypestringAn optional field to indicate to transformer plugins that your node has raw content they can transform. Use either an official media type (we use mime-db as our source (https://www.npmjs.com/package/mime-db) or a made-up one if your data doesn’t fit in any existing bucket. Transformer plugins use node media types for deciding if they should transform a node into a new one. E.g. markdown transformers look for media types of
text/markdown.typestringAn arbitrary globally unique type chosen by the plugin creating the node. Should be descriptive of the node as the type is used in forming GraphQL types so users will query for nodes based on the type chosen here. Nodes of a given type can only be created by one plugin.
contentstringAn optional field. This is rarely used. It is used when a source plugin sources data it doesn’t know how to transform e.g. a markdown string pulled from an API. The source plugin can defer the transformation to a specialized transformer plugin like gatsby-transformer-remark. This
contentfield holds the raw content (so for the markdown case, the markdown string).Data that’s already structured should be added to the top-level of the node object and not added here. You should not
JSON.stringifyyour node’s data here.If the content is very large and can be lazy-loaded, e.g. a file on disk, you can define a
loadNodeContentfunction for this node and the node content will be lazy loaded when it’s needed.contentDigeststringthe digest for the content of this node. Helps Gatsby avoid doing extra work on data that hasn’t changed.
descriptionstringAn optional field. Human readable description of what this node represent / its source. It will be displayed when type conflicts are found, making it easier to find and correct type conflicts.
pluginPluginactionOptionsActionOptions
Return value
Promise
The returned Promise resolves when all cascading
onCreateNode API calls triggered by createNode have finished.
Example
createNode({
// Data for the node.
field1: `a string`,
field2: 10,
field3: true,
...arbitraryOtherData,
// Required fields.
id: `a-node-id`,
parent: `the-id-of-the-parent-node`, // or null if it's a source node without a parent
children: [],
internal: {
type: `CoolServiceMarkdownField`,
contentDigest: crypto
.createHash(`md5`)
.update(JSON.stringify(fieldData))
.digest(`hex`),
mediaType: `text/markdown`, // optional
content: JSON.stringify(fieldData), // optional
description: `Cool Service: "Title of entry"`, // optional
}
})Source
Extend another node. The new node field is placed under the fields
key on the extended node object.
Once a plugin has claimed a field name the field name can’t be used by other plugins. Also since nodes are immutable, you can’t mutate the node directly. So to extend another node, use this.
Parameters
- destructured object
nodeObjectthe target node object
namestringthe name for the field
valueanythe value for the field
fieldNamestring[deprecated] the name for the field
fieldValuestring[deprecated] the value for the field
pluginPluginactionOptionsActionOptions
Example
createNodeField({
node,
name: `happiness`,
value: `is sweet graphql queries`
})
// The field value is now accessible at node.fields.happinessSource
Create a page. See the guide on creating and modifying pages for detailed documentation about creating pages.
Parameters
pageObjecta page object
pathstringAny valid URL. Must start with a forward slash
matchPathstringPath that Reach Router uses to match the page on the client side. Also see docs on matchPath
componentstringThe absolute path to the component for this page
contextObjectContext data for this page. Passed as props to the component
this.props.pageContextas well as to the graphql query as graphql arguments.
pluginPluginactionOptionsActionOptions
Example
createPage({
path: `/my-sweet-new-page/`,
component: path.resolve(`./src/templates/my-sweet-new-page.js`),
// The context is passed as props to the component as well
// as into the component's GraphQL query.
context: {
id: `123456`,
},
})Source
Creates a link between a parent and child node. This is used when you
transform content from a node creating a new child node. You need to add
this new child node to the children array of the parent but since you
don’t have direct access to the immutable parent node, use this action
instead.
Parameters
- destructured object
parentObjectthe parent node object
childObjectthe child node object
pluginPlugin
Example
createParentChildLink({ parent: parentNode, child: childNode })Source
Create a redirect from one page to another. Server redirects don’t work out of the box. You must have a plugin setup to integrate the redirect data with your hosting technology e.g. the Netlify plugin, or the Amazon S3 plugin. Alternatively, you can use this plugin to generate meta redirect html files for redirecting on any static file host.
Parameters
redirectObjectRedirect data
fromPathstringAny valid URL. Must start with a forward slash
isPermanentbooleanThis is a permanent redirect; defaults to temporary
redirectInBrowserbooleanRedirects are generally for redirecting legacy URLs to their new configuration. If you can’t update your UI for some reason, set
redirectInBrowserto true and Gatsby will handle redirecting in the client as well.toPathstringURL of a created page (see
createPage)forceboolean(Plugin-specific) Will trigger the redirect even if the
fromPathmatches a piece of content. This is not part of the Gatsby API, but implemented by (some) plugins that configure hosting provider redirectsstatusCodenumber(Plugin-specific) Manually set the HTTP status code. This allows you to create a rewrite (status code 200) or custom error page (status code 404). Note that this will override the
isPermanentoption which also sets the status code. This is not part of the Gatsby API, but implemented by (some) plugins that configure hosting provider redirectsrest
Example
// Generally you create redirects while creating pages.
exports.createPages = ({ graphql, actions }) => {
const { createRedirect } = actions
createRedirect({ fromPath: '/old-url', toPath: '/new-url', isPermanent: true })
createRedirect({ fromPath: '/url', toPath: '/zn-CH/url', Language: 'zn' })
createRedirect({ fromPath: '/not_so-pretty_url', toPath: '/pretty/url', statusCode: 200 })
// Create pages here
}Source
Make functionality available on field resolver context
Parameters
contextobjectObject to make available on
context. When called from a plugin, the context value will be namespaced under the camel-cased plugin name without the “gatsby-” prefixpluginIGatsbyPlugintraceIdstring
Return value
ThunkAction<>
Example
const getHtml = md => remark().use(html).process(md)
exports.createSchemaCustomization = ({ actions }) => {
actions.createResolverContext({ getHtml })
}
// The context value can then be accessed in any field resolver like this:
exports.createSchemaCustomization = ({ actions, schema }) => {
actions.createTypes(schema.buildObjectType({
name: 'Test',
interfaces: ['Node'],
fields: {
md: {
type: 'String!',
async resolve(source, args, context, info) {
const processed = await context.transformerRemark.getHtml(source.internal.contents)
return processed.contents
}
}
}
}))
}Source
Record that a page was visited on the server..
Parameters
chunkNamestring- destructured object
idstringthe chunkName for the page component.
Source
Add type definitions to the GraphQL schema.
Parameters
typesstring | GraphQLOutputType | GatsbyGraphQLType | string[] | GraphQLOutputType[] | GatsbyGraphQLType[]Type definitions
Type definitions can be provided either as
graphql-jstypes, in GraphQL schema definition language (SDL) or using Gatsby Type Builders available on theschemaAPI argument.Things to note:
- type definitions targeting node types, i.e.
MarkdownRemarkand others added insourceNodesoronCreateNodeAPIs, need to implement theNodeinterface. Interface fields will be added automatically, but it is mandatory to label those types withimplements Node. - by default, explicit type definitions from
createTypeswill be merged with inferred field types, and default field resolvers forDate(which adds formatting options) andFile(which resolves the field value as arelativePathforeign-key field) are added. This behavior can be customised with@infer,@dontInferdirectives or extensions. Fields may be assigned resolver (and other option like args) with additional directives. Currently@dateformat,@link,@fileByRelativePathand@proxyare available.
Schema customization controls:
@infer- run inference on the type and add fields that don’t exist on the
defined type to it.
@dontInfer- don’t run any inference on the type
Extensions to add resolver options:
@dateformat- add date formatting arguments. AcceptsformatStringandlocaleoptions that sets the defaults for this field@link- connect to a different Node. Argumentsbyandfrom, which define which field to compare to on a remote node and which field to use on the source node@fileByRelativePath- connect to a File node. Same arguments. The difference from link is that this normalizes the relative path to be relative from the path where source node is found.@proxy- in case the underlying node data contains field names with characters that are invalid in GraphQL,proxyallows to explicitly proxy those properties to fields with valid field names. Takes afromarg.
- type definitions targeting node types, i.e.
pluginIGatsbyPlugintraceIdstring
Return value
ICreateTypes
Example
exports.createSchemaCustomization = ({ actions }) => {
const { createTypes } = actions
const typeDefs = `
"""
Markdown Node
"""
type MarkdownRemark implements Node @infer {
frontmatter: Frontmatter!
}
"""
Markdown Frontmatter
"""
type Frontmatter @infer {
title: String!
author: AuthorJson! @link
date: Date! @dateformat
published: Boolean!
tags: [String!]!
}
"""
Author information
"""
# Does not include automatically inferred fields
type AuthorJson implements Node @dontInfer {
name: String!
birthday: Date! @dateformat(locale: "ru")
}
`
createTypes(typeDefs)
}
// using Gatsby Type Builder API
exports.createSchemaCustomization = ({ actions, schema }) => {
const { createTypes } = actions
const typeDefs = [
schema.buildObjectType({
name: 'MarkdownRemark',
fields: {
frontmatter: 'Frontmatter!'
},
interfaces: ['Node'],
extensions: {
infer: true,
},
}),
schema.buildObjectType({
name: 'Frontmatter',
fields: {
title: {
type: 'String!',
resolve(parent) {
return parent.title || '(Untitled)'
}
},
author: {
type: 'AuthorJson'
extensions: {
link: {},
},
}
date: {
type: 'Date!'
extensions: {
dateformat: {},
},
},
published: 'Boolean!',
tags: '[String!]!',
}
}),
schema.buildObjectType({
name: 'AuthorJson',
fields: {
name: 'String!'
birthday: {
type: 'Date!'
extensions: {
dateformat: {
locale: 'ru',
},
},
},
},
interfaces: ['Node'],
extensions: {
infer: false,
},
}),
]
createTypes(typeDefs)
}Source
Delete a node
Parameters
optionspluginPluginargs- destructured object
nodeobjectthe node object
Example
deleteNode({node: node})Source
Delete a page
Parameters
pageObjecta page object
pathstringThe path of the page
componentstringThe absolute path to the page component
Example
deletePage(page)Source
Write GraphQL schema to file
Writes out inferred and explicitly specified type definitions. This is not the full GraphQL schema, but only the types necessary to recreate all type definitions, i.e. it does not include directives, built-ins, and derived types for filtering, sorting, pagination etc. Optionally, you can define a list of types to include/exclude. This is recommended to avoid including definitions for plugin-created types.
The first object parameter is required, however all the fields in the object are optional.
Parameters
- destructured object
pathstringThe path to the output file, defaults to
schema.gqlincludeobjectConfigure types to include
typesstring[]Only include these types
pluginsstring[]Only include types owned by these plugins
excludeobjectConfigure types to exclude
typesstring[]Do not include these types
pluginsstring[]Do not include types owned by these plugins
withFieldTypesbooleanInclude field types, defaults to
true
pluginIGatsbyPlugintraceIdstring
Return value
IPrintTypeDefinitions
Example
exports.createSchemaCustomization = ({ actions }) => {
// This code writes a GraphQL schema to a file named `schema.gql`.
actions.printTypeDefinitions({})
}exports.createSchemaCustomization = ({ actions }) => {
// This code writes a GraphQL schema to a file named `schema.gql`, but this time it does not include field types.
actions.printTypeDefinitions({ withFieldTypes: false })
}Source
Remove page data from the store.
Parameters
idPageDataRemove- destructured object
idstringthe path to the page.
Source
Completely replace the webpack config for the current stage. This can be dangerous and break Gatsby if certain configuration options are changed.
Generally only useful for cases where you need to handle config merging logic
yourself, in which case consider using webpack-merge.
Parameters
configObjectcomplete webpack config
plugin
Source
Set top-level Babel options. Plugins and presets will be ignored. Use setBabelPlugin and setBabelPreset for this.
Parameters
optionsObjectpluginconfigObjectAn options object in the shape of a normal babelrc JavaScript object
Example
setBabelOptions({
options: {
sourceMaps: `inline`,
}
})Source
Add new plugins or merge options into existing Babel plugins.
Parameters
configObjectA config object describing the Babel plugin to be added.
namestringThe name of the Babel plugin
optionsObjectOptions to pass to the Babel plugin.
plugin
Example
setBabelPlugin({
name: `@emotion/babel-plugin`,
options: {
sourceMap: true,
},
})Source
Add new presets or merge options into existing Babel presets.
Parameters
configObjectA config object describing the Babel plugin to be added.
namestringThe name of the Babel preset.
optionsObjectOptions to pass to the Babel preset.
plugin
Example
setBabelPreset({
name: `@babel/preset-react`,
options: {
pragma: `Glamor.createElement`,
},
})Source
Set page data in the store, saving the pages content data and context.
Parameters
pageDataPageData- destructured object
idstringthe path to the page.
resultHashstringpages content hash.
Source
Set plugin status. A plugin can use this to save status keys e.g. the last it fetched something. These values are persisted between runs of Gatsby.
Parameters
statusObjectAn object with arbitrary values set
pluginPlugin
Example
setPluginStatus({ lastFetched: Date.now() })Source
Merge additional configuration into the current webpack config. A few
configurations options will be ignored if set, in order to try prevent accidental breakage.
Specifically, any change to entry, output, target, or resolveLoaders will be ignored.
For full control over the webpack config, use replaceWebpackConfig().
Parameters
configObjectpartial webpack config, to be merged into the current one
plugin
Source
Memoize function used to pick shadowed page components to avoid expensive I/O. Ideally, we should invalidate memoized values if there are any FS operations on files that are in shadowing chain, but webpack currently doesn’t handle shadowing changes during develop session, so no invalidation is not a deal breaker.
Source
“Touch” a node. Tells Gatsby a node still exists and shouldn’t be garbage collected. Primarily useful for source plugins fetching nodes from a remote system that can return only nodes that have updated. The source plugin then touches all the nodes that haven’t updated but still exist so Gatsby knows to keep them.
Parameters
optionspluginPlugin- destructured object
nodeIdstringThe id of a node
Example
touchNode({ nodeId: `a-node-id` })