Setting Up Live Preview with Craft CMS in Headless Mode
import { json } from 'remix'
import { gql } from 'graphql-request'
import { gqlClient } from 'graphql.server'
export const loader = async ({ request }) => {
const { entries } = await gqlClient(request).request(gql`
{
YOUR GRAPHQL QUERY HERE
}
`)
return json({ entries })
}
import { GraphQLClient } from 'graphql-request'
// Extract allowed query params and construct query string
const getQueryParams = (request) => {
const url = new URL(request.url)
const allowedKeys = ['x-craft-preview', 'x-craft-live-preview', 'token']
const filteredParams = Object.entries(
Object.fromEntries(url.searchParams)
).filter(([key]) => allowedKeys.includes(key))
if (!filteredParams.length) {
return ''
}
const queryString = filteredParams.map((val) => val.join('=')).join('&')
return `?${queryString}`
}
export const gqlClient = (request = null) => {
const queryString = request ? getQueryParams(request) : ''
return new GraphQLClient(`https://your-endpoint-here/${queryString}`, {
headers: {
authorization: `Bearer YOUR_AUTH_TOKEN_HERE`,
},
})
}
<?php
return [
'*' => [
'headlessMode' => true,
'previewIframeResizerOptions' => [
'checkOrigin' => [
'https://www.trevor-davis.com',
],
],
],
];