Next.js Preview in iFrames

This FAQ shows a potential solution while integrating NextJs’ Preview Mode within an iframe while running on localhost. This is something you might face during the integration with our Visual Editor since its using an iframe.

The Challenge

To work correctly, the Next’s Preview Mode needs to set two special cookies: __prerender_bypass and __next_preview_data.

Only when we try to visualize the page inside the an iframe, the cookies cannot be set due to the error:

“This Set-Cookie was blocked because it had the “SameSite=Lax” attribute but came from a cross-site response which was not the response to a top-level navigation”.

This is due to Browser Security configurations for cookies. You now have two possibilities to work with it.

Option 1:

You can disable the chrome flag. You can completely disable this feature by going to chrome://flags and disabling “Cookies without SameSite must be secure”.

However, this will disable it for all sites, so it will be less secure when you aren’t developing too. So either make sure to enable it once you’re done or try the next option.

Option 2:

We’ve extracted the code of Next.js that sets the cookie and you can now set the cookie yourself in your preview.js with the correct settings when on localhost.

export default (req, res) => {
  // ...
  const previous = res.getHeader('Set-Cookie')
  previous.forEach((cookie, index) => {
    previous[index] = cookie.replace('SameSite=Lax', 'SameSite=None')
  res.setHeader(`Set-Cookie`, previous)
  res.end("Preview mode enabled")
  // ...

Now you would also need to set-up your localhost using a self signed certificate so you can use https://localhost rather than http://localhost.