Last active
October 16, 2020 19:03
-
-
Save monachilada/af7e92a86e0d27ba47a8597ac4e4b105 to your computer and use it in GitHub Desktop.
Sample gatsby-config.js enabling live preview in Craft CMS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { createHttpLink } = require('apollo-link-http'); | |
const fetch = require('node-fetch'); | |
const store = require('store'); | |
const sourceNodes = require('gatsby/dist/utils/source-nodes'); | |
require('dotenv').config(); | |
const craftGqlUrl = process.env.CRAFT_GQL_URL; | |
const craftGqlToken = process.env.CRAFT_GQL_TOKEN; | |
module.exports = { | |
plugins: [ | |
{ | |
resolve: 'gatsby-source-graphql', | |
options: { | |
typeName: 'Craft', | |
fieldName: 'craft', | |
createLink: () => | |
createHttpLink({ | |
uri: `${craftGqlUrl}`, | |
headers: { | |
Authorization: `Bearer ${craftGqlToken}`, | |
}, | |
fetch: (uri, options) => { | |
const token = store.get('X-Craft-Token'); | |
return fetch( | |
`${uri}${token !== undefined ? `?token=${token}` : ''}`, | |
options, | |
); | |
}, | |
}), | |
}, | |
}, | |
], | |
developMiddleware: app => { | |
app.use('*', (req, res, next) => { | |
if (req.query.token) { | |
store.set('X-Craft-Token', req.query.token); | |
sourceNodes(); | |
} | |
next(); | |
}); | |
}, | |
}; |
@wfendler Did you manage to figure out your latest draft issue, I have hit the same problem...
@jamie-l-robertson I haven't. After making several attempts I've given up until we have better Gatsby + Craft support through a new source plugin. It seems like this is coming soon: https://github.com/craftcms/craft-gatsby
Discord conversation starts around here: https://discordapp.com/channels/456442477667418113/629094175509446657/752907415003070514
@wfendler Ah excellent, thanks for the heads up!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So, I kind of got this working. I definitely need a deeper understanding of middleware and how
createLink
andcreateHttpLink
work to finish this up but perhaps someone else on here could help me out.By adding
createSchemaCustomization
and fixing thesourceNodes
reference I was able to get this close. The problem here is that when Craft loads this in the iframe it doesn't load the latest draft. IfrefetchInterval
is set however, it will load the correct content whenever that interval fetches new data. So, for now I just have the interval set to 30 seconds so content editors don't see changes immediately but they rarely have to wait long to see updates.Does anyone else see what's wrong in here? We're hosting this on Heroku, running
gatsby develop -p $PORT -H 0.0.0.0
(based on this article by @andreaskeller)