useQuerySubscription
Another common scenario is being able to activate real-time updates of draft content only for content editors that are signed-in to the website via Preview Mode:
In this case, you don't want to expose your API token or pass down additional arguments to regular users, so:
Make sure to pass the includeDrafts: true
option only if Preview Mode is active (that is, if context.preview
is true), so that only content editors will see draft content;
Use NEXT_
instead of NEXT_PUBLIC_
as the prefix for our env variable, so that the token will only be readable server-side;
If Preview Mode is off, fill in the subscription
prop with just initialData
and enabled: false
options, without any additional clutter.
Here's an example snippet:
export async function getStaticProps(context) {const graphqlRequest = {query: HOMEPAGE_QUERY,variables: { limit: 10 },// If true, the Content Delivery API with draft content will be usedincludeDrafts: context.preview,};return {props: {subscription: context.preview? {...graphqlRequest,initialData: await request(graphqlRequest),token: process.env.NEXT_DATOCMS_API_TOKEN,}: {enabled: false,initialData: await request(graphqlRequest),},},};}
If you want to directly see the final result, we've prepared a fully working Next.js blog, with real-time updates of draft content in Preview Mode: