Hello prismic people.
Im having some difficulties setting up previews with prismic and nextjs. My problem is that when i do hit the preview api endpoint, the redirect work and a ref for the preview are being passed to getStaticProps.
In getStaticProps im able to fetch the preview data by passing the ref to the client options ( is this the prefered way? the nextjs part of the prismic docs say nothing about how to do this btw)
But all my other calls with the client, that are supposed to return data from the master ref(my hope is) doesn't return anything.
The other calls i make are for global stuff like the header and footer components, so they are never in a preview-state. Do all calls via the client use the new ref in some way or is it possible to make these requests still work in preview mode?
I've tried setting the query options ref to the master ref when in preview on those other calls but it didn't make a difference, example below:
const api = await client.getApi()
const global = (await client.getSingle('global_layout', { lang: locale, ref: })) || {}
const allPosts = (await client.query(Prismic.Predicates.at('document.type', 'blog_post'), { lang: locale, ref: api.data.masterRef.ref })) || {}
My client:
const apiEndpoint = 'https://myproject.cdn.prismic.io/api/v2'
export const client = Prismic.client(apiEndpoint)
My preview endpoint (nevermind the linkresolver, its temporarly and not the problem :):
import { client } from 'lib/prismic/client'
import { linkResolver } from 'lib/prismic/link-resolver'
export default async function preview(req, res) {
const { token: ref, documentId } = req.query
const url = await client.getPreviewResolver(ref, documentId).resolve(linkResolver({type: 'blog_post', uid: '/news/vinden-levererar-till-din-dorr'}), '/news/vinden-levererar-till-din-dorr')
if (!url) {
return res.status(401).json({ message: 'Invalid token' })
}
res.setPreviewData({
ref, // pass the ref to pages so that they can fetch the draft ref
})
res.write(
`<!DOCTYPE html><html><head><meta http-equiv="Refresh" content="0; url=${url}" />
<script>window.location.href = '${url}'</script>
</head>`
)
res.end()
}
getStaticProps:
export async function getStaticProps({ params, locale, preview = false, previewData }) {
let posts
if (preview) {
const { ref } = previewData
posts = (await client.getByUID('blog_post', params.uid, { ref })) || {}
} else {
posts = (await client.getByUID('blog_post', params.uid, { lang: locale })) || {}
}
const global = (await client.getSingle('global_layout', { lang: locale })) || {}
const allPosts = (await client.query(Prismic.Predicates.at('document.type', 'blog_post'), { lang: locale })) || {}
return {
props: {
posts,
global,
allPosts,
},
}
}
Hope someone knows what could be the problem since that would make my day!
/ Hugo