- Notifications
You must be signed in to change notification settings - Fork58
Gatsby source plugin for building websites using Sanity.io as a backend.
sanity-io/gatsby-source-sanity
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Gatsby source plugin for pulling data fromSanity.io intoGatsby websites. Develop with real-time preview of all content changes. Compatible withgatsby-plugin-image. Uses your project's GraphQL schema definitions to avoid accidental missing fields (no dummy-content needed).
Get up and running in minutes with a fully configured starter project:
- Install
- Basic usage
- Options
- Preview of unpublished content
- GraphQL API
- Using images
- Generating pages
- "Raw" fields
- Portable Text / Block Content
- Using multiple datasets
- Real-time content preview with watch mode
- Updating content for editors with preview servers
- Using .env variables
- How this source plugin works
- Credits
- Develop
From the command line, use npm (node package manager) to install the plugin:
npm install gatsby-source-sanity gatsby-plugin-imagegatsby-plugin-image which itself has dependencies. Checkgatsby-plugin-image README for instructions.
In thegatsby-config.js file in the Gatsby project's root directory, add the plugin configuration inside of theplugins section:
module.exports={// ...plugins:[{resolve:`gatsby-source-sanity`,options:{projectId:`abc123`,dataset:`blog`,// a token with read permissions is required// if you have a private datasettoken:process.env.SANITY_TOKEN,// If the Sanity GraphQL API was deployed using `--tag <name>`,// use `graphqlTag` to specify the tag name. Defaults to `default`.graphqlTag:'default',},},`gatsby-plugin-image`,// ...],// ...}
You can accessprojectId anddataset by executingsanity debug --secrets in the Sanity studio folder. Note that the token printed may be used for development, but is tied to your Sanity CLI login session using your personal Sanity account - make sure to keep it secure and not include it in version control! For production, you'll want to make sure you use a read token generate in the Sanitymanagement interface.
At this point you shouldset up a GraphQL API for your Sanity dataset, if you have not done so already. This will help the plugin in knowing which types and fields exists, so you can query for them even without them being present in any current documents.
You should redeploy the GraphQL API everytime you make changes to the schema that you want to use in Gatsby by runningsanity graphql deploy from within your Sanity project directory
Explorehttp://localhost:8000/___graphql after runninggatsby develop to understand the created data and create a new query and checking available collections and fields by typingCtrl + Space.
| Options | Type | Default | Description |
|---|---|---|---|
| projectId | string | [required] Your Sanity project's ID | |
| dataset | string | [required] The dataset to fetch from | |
| token | string | Authentication token for fetching data from private datasets, or when usingoverlayDraftsLearn more | |
| graphqlTag | string | default | If the Sanity GraphQL API was deployed using--tag <name>, use this to specify the tag name. |
| overlayDrafts | boolean | false | Set totrue in order for drafts to replace their published version. By default, drafts will be skipped. |
| watchMode | boolean | false | Set totrue to keep a listener open and update with the latest changes in realtime. If you add atoken you will get all content updates down to each key press. |
| watchModeBuffer | number | 150 | How many milliseconds to wait on watchMode changes before applying them to Gatsby's GraphQL layer. Introduced in 7.2.0. |
| typePrefix | string | Prefix to use for the GraphQL types. This is prepended toSanity in the type names and allows you to have multiple instances of the plugin in your Gatsby project. |
Sometimes you might be working on some new content that is not yet published, which you want to make sure looks alright within your Gatsby site. By setting theoverlayDrafts setting totrue, the draft versions will as the option says "overlay" the regular document. In terms of Gatsby nodes, it willreplace the published document with the draft.
Keep in mind that drafts do not have to conform to any validation rules, so your frontend will usually want to double-check all nested properties before attempting to use them.
Bydeploying a GraphQL API for your dataset, we are able to introspect and figure out which schema types and fields are available and make informed choices based on this information.
Previous versions did notrequire this, but often lead to very confusing and unpredictable behavior, which is why we have now made it a requirement.
Image fields will have the image URL available under thefield.asset.url key, but you can also usegatsby-plugin-image for a smooth experience. It's a React component that enables responsive images and advanced image loading techniques. It works great with this source plugin, without requiring any additional build steps.
importReactfrom'react'import{GatsbyImage}from'gatsby-plugin-image'constsanityConfig={projectId:'abc123',dataset:'blog'}constPerson=({data})=>{return(<article><h2>{data.sanityPerson.name}</h2><GatsbyImageimage={data.sanityPerson.profileImage.asset.gatsbyImageData}/></article>)}exportdefaultPersonexportconstquery=graphql` query PersonQuery { sanityPerson { name profileImage { asset { gatsbyImageData(fit: FILLMAX, placeholder: BLURRED) } } } }`
Note: we currentlydon't support theformat option ofgatsbyImageData. Our image CDN automatically serves the best format for the user depending on their device, so you don't need to define formats manually.
This plugin supportsGatsby's new Image CDN feature. To use it, follow the instructions in the section above, but substitute thegatsbyImageData field forgatsbyImage.
If you are using the raw fields, or simply have an image asset ID you would like to usegatsby-plugin-image for, you can import and call the utility functiongetGatsbyImageData
import{GatsbyImage}from'gatsby-plugin-image'import{getGatsbyImageData}from'gatsby-source-sanity'constsanityConfig={projectId:'abc123',dataset:'blog'}constimageAssetId='image-488e172a7283400a57e57ffa5762ac3bd837b2ee-4240x2832-jpg'constimageData=getGatsbyImageData(imageAssetId,{maxWidth:1024},sanityConfig)<GatsbyImageimage={imageData}/>
Sanity does not have any concept of a "page", since it's built to be totally agnostic to how you want to present your content and in which medium, but since you're using Gatsby, you'll probably want some pages!
As with any Gatsby site, you'll want to create agatsby-node.js in the root of your Gatsby site repository (if it doesn't already exist), and declare acreatePages function. Within it, you'll use GraphQL to query for the data you need to build the pages.
For instance, if you have aproject document type in Sanity that you want to generate pages for, you could do something along the lines of this:
exports.createPages=async({graphql, actions})=>{const{createPage}=actionsconstresult=awaitgraphql(` { allSanityProject(filter: {slug: {current: {ne: null}}}) { edges { node { title description tags launchDate(format: "DD.MM.YYYY") slug { current } image { asset { url } } } } } } `)if(result.errors){throwresult.errors}constprojects=result.data.allSanityProject.edges||[]projects.forEach((edge,index)=>{constpath=`/project/${edge.node.slug.current}`createPage({ path,component:require.resolve('./src/templates/project.js'),context:{slug:edge.node.slug.current},})})}
The above query will fetch all projects that have aslug.current field set, and generate pages for them, available as/project/<project-slug>. It will use the template defined insrc/templates/project.js as the basis for these pages.
CheckoutCreating Pages from Data Programmatically to learn more.
Remember to use the GraphiQL interface to help write the queries you need - it's usually running athttp://localhost:8000/___graphql while runninggatsby develop.
Arrays and object types at the root of documents will get an additional "raw JSON" representation in a field called_raw<FieldName>. For instance, a field namedbody will be mapped to_rawBody. It's important to note that this is only done for top-level nodes (documents).
Quite often, you'll want to replace reference fields (eg_ref: '<documentId>'), with the actual document that is referenced. This is done automatically for regular fields, but within raw fields, you have to explicitly enable this behavior, by using the field-levelresolveReferences argument:
{allSanityProject {edges {node {_rawTasks(resolveReferences: {maxDepth:5}) } } }}Rich text in Sanity is usually represented asPortable Text (previously known as "Block Content").
These data structures can be deep and a chore to query (specifying all the possible fields). Asnoted above, there is a "raw" alternative available for these fields which is usually what you'll want to use.
You can install@portabletext/react from npm and use it in your Gatsby project to serialize Portable Text. It lets you use your own React components to override defaults and render custom content types.Learn more about Portable Text in our documentation.
If you want to use more than one dataset in your site, you can do so by adding multiple instances of the plugin to yourgatsby-config.js file. To avoid conflicting type names you can use thetypeName option to set a custom prefix for the GraphQL types. These can be datasets from different projects, or different datasets within the same project.
// In your gatsby-config.jsmodule.exports={plugins:[{resolve:'gatsby-source-sanity',options:{projectId:'abc123',dataset:'production',},},{resolve:'gatsby-source-sanity',options:{projectId:'abc123',dataset:'staging',typePrefix:'Staging',},},],}
In this case, the type names for the first instance will beSanity<typeName>, while the second will beStagingSanity<typeName>.
While developing, it can often be beneficial to get updates without having to manually restart the build process. By settingwatchMode to true, this plugin will set up a listener which watches for changes. When it detects a change, the document in question is updated in real-time and will be reflected immediately.
If you addatoken with read rights and setoverlayDrafts to true, each small change to the draft will immediately be applied. Keep in mind that this is mainly intended for development, see next section for how to enable previews for your entire team.
You can useGatsby preview servers (often throughGatsby Cloud) to update your content on a live URL your team can use.
In order to have previews working, you'll need to activateoverlayDrafts in the plugin's configuration inside preview environments. To do so, we recommend following a pattern similar to this:
// In gatsby-config.jsconstisProd=process.env.NODE_ENV==="production"constpreviewEnabled=(process.env.GATSBY_IS_PREVIEW||"false").toLowerCase()==="true"module.exports={// ...plugins:[resolve:"gatsby-source-sanity",options:{// ...watchMode:!isProd,// watchMode only in dev modeoverlayDrafts:!isProd||previewEnabled,// drafts in dev & Gatsby Cloud Preview},]}
Then, you'll need to set-up a Sanity webhook pointing to your Gatsby preview URL. Create your webhook fromthis template, making sure you update the URL.
If using Gatsby Cloud, this should be auto-configured during your initial set-up.
You can also follow the manual steps below:
Get the webhook endpoint needed for triggering Gatsby Cloud previews intheir dashboard.
Go tosanity.io/manage and navigate to your project
Under the "API" tab, scroll to Webhooks or "GROQ-powered webhooks"
Add a new webhook and name it as you see fit
Choose the appropriate dataset and add the Gatsby Cloud webhook endpoint to the URL field
Keep the HTTP method set to POST, skip "HTTP Headers"
Set the hook to trigger on Create, Update and Delete
Skip the filter field
Specify the following projection:
select(delta::operation()=="delete"=>{"operation":delta::operation(),"documentId":coalesce(before()._id,after()._id),"projectId":sanity::projectId(),"dataset":sanity::dataset(),},{})
Set the API version to
v2021-03-25And set it to fire on drafts
Save the webhook
If you don't want to attach your Sanity project's ID to the repo, you can easily store it in .env files by doing the following:
// In your .env fileSANITY_PROJECT_ID=abc123SANITY_DATASET=productionSANITY_TOKEN=my_super_secret_token// In your gatsby-config.js filerequire('dotenv').config({path:`.env.${process.env.NODE_ENV}`,})module.exports={// ...plugins:[{resolve:'gatsby-source-sanity',options:{projectId:process.env.SANITY_PROJECT_ID,dataset:process.env.SANITY_DATASET,token:process.env.SANITY_TOKEN,// ...},},],// ...}
This example is based offGatsby Docs' implementation.
When starting Gatsby in development or building a website, the source plugin will first fetch the GraphQL Schema Definitions from a Sanity deployed GraphQL API. The source plugin uses this to tell Gatsby which fields should be available to prevent it from breaking if the content for certain fields happens to disappear. Then it will hit the project’s export endpoint, which streams all the accessible documents to Gatsby’s in-memory datastore.
In other words, the whole site is built with two requests. Running the development server, will also set up a listener that pushes whatever changes come from Sanity to Gatsby in real-time, without doing additional API queries. If you give the source plugin a token with permission to read drafts, you’ll see the changes instantly.
Huge thanks toHenrique Doro for doing the initial implementation of this plugin, and for donating it to the Sanity team. Mad props!
Big thanks to the good people backing Gatsby for bringing such a joy to our developer days!
Run"CI & Release" workflow.Make sure to select the main branch and check "Release new version".
Semantic release will only release on configured branches, so it is safe to run release on any branch.
About
Gatsby source plugin for building websites using Sanity.io as a backend.
Topics
Resources
Code of conduct
Security policy
Uh oh!
There was an error while loading.Please reload this page.
