Prismic /api route to serverless functions

Hi. Full disclosure, I’m relatively new to both NextJS and Prismic, and a complete Netlify function newb. This may be super easy. I am trying to get the preview function in Prismic to work on my Netlify site. Part of the Prismic support forums indicated the reason is that the /api/preview.js route isn’t natively routed by Netlify, and is natively converted to serverless functions on platforms like Vercel. So, I think I need to convert the preview.js into some kind of Netlify function, but I’m not sure where to start, even after reading the functions documentation. The preview.js file looks like this:

import { Client, linkResolver } from "../../prismic-configuration"

export default async (req, res) => {
    console.log("In Preview.js");
  const { token: ref, documentId } = req.query;
  const redirectUrl = await Client(req)
    .getPreviewResolver(ref, documentId)
    .resolve(linkResolver, '/');

  if (!redirectUrl) {
    return res.status(401).json({ message: 'Invalid token' });
  }

  res.setPreviewData({ ref });

  res.write(
    `<!DOCTYPE html><html><head><meta http-equiv="Refresh" content="0; url=${redirectUrl}" />
    <script>window.location.href = '${redirectUrl}'</script>
    </head>`
  );
  res.end();
};

Any help would be super appreciated. This is my last hurdle with this project. Everything else has been breezy with Netlify.

Hi @asummers,

Most of the NextJS API is handled by Next On Netlify so it usually works well. Your example might not be one of those.

Getting help with it might be difficult. The above code cannot be natively converted to Netlify Functions without knowing what some of those parameters actually do (for example, res). The Support Team might not have the bandwidth to be able to get this working for you.

With that being said, there are some awesome Pilots around the forums who might be willing to help. However, there are chances that you might not be able to get the help you need.

If you do get it to work, do share. It might help someone else.

Yeah, I will definitely share if I’m able to get it to work. I know others have gotten it to work, so at least I know it’s possible. But I get your point - this is not really a Netlify specific issue. :slight_smile: