Prismic preview not working with Sapper

Hi,

I'm having issues with the preview of draft documents. I followed this guide to seeting it up - Previews and the Prismic Toolbar with NodeJS - Prismic and everything works except it shows the latest published version instead of the draft version. I also followed the troubleshooting page and couldn't find the issue (Troubleshooting: Previews | Prismic Help Center), what could be the cause of it?

Here's the server code

// preview.js 
import { linkResolver, Client } from '../utils/prismicHelpers';

export async function get(req, res, next) {
  const { token, documentId } = req.query;
  const api = await Client();
  const redirectUrl = await api.getPreviewResolver(token, documentId).resolve(linkResolver, '/');
  res.redirect(302, redirectUrl);
}

I'm using "@prismicio/client": "^4.0.0".

Hey @kristian1,

Thanks for posting this question. I haven't played with previews in Svelte, yet, but I'll give it a try and let you know if I find anything that might be helpful for your use case :slight_smile:

Sam

Hey @kristian1,

I figured this out with SvelteKit, and I think the solution might be similar in Sapper.

In your page component, you need to pass the req object when you initialize the client. But, in SvelteKit, the req object doesn't seem to be plainly accessible in the page components.

req contains a preview cookie. When you pass the req object to the client, in adds the cookie to the API query to allow you to query preview content.

SvelteKit has two hooks: handle() and getSession(). I used getSession() to get the cookie and pass it to my page component in a session argument. I'm not sure what the Sapper equivalent of this would be, but it might be similar.

Here's the diff view, so you can see the changes I made to add previews:

Take a look and let me know if that makes sense. If it doesn't seem to make sense, I can try to set up a Sapper project and get previews working.

Sam