All questions

Getting an error calling the SDK during Nuxt server render

Asked by dmitri on

Ddmitri

I have client-only SDK logic that is running during the server render pass in Nuxt and it throws. The error fires while the server is rendering, before the page reaches the browser, so it looks like a hydration-time problem.

Please how I fix this so personalization works with SSR instead of blowing up on the server pass? I paste the gist below but the shape is: a call meant for the client is executing on the server.

Was this helpful?

2 answers

Ssam_the_devAccepted answer

This is a known one and it is documented across the React, Vue, and Hydrogen SDKs, so you are not doing anything exotic. The rule is that client-only SDK logic must not run during the server render pass.

The fix is to resolve the content on the server the supported way and pass the result down as data, rather than calling client-side APIs while the server is rendering. In Nuxt that means doing the fetch in useAsyncData so it runs in the server pass and hands the resolved content to your component:

const {data} = await useAsyncData('home-hero', () =>    croct.fetch('home-hero@2').catch(() => ({content: {/* defaults */}})),);

Resolving server-side like this is also what keeps the initial HTML correct with no flicker, so you get the fix and the no-flash behaviour at once.

Was this helpful?
Oola_v

To add the other half: the interactive client-side calls (tracking a click, evaluating something on an interaction) are fine, they just have to live in code that only runs after mount, not during the server pass. So content resolution goes server-side, and anything that reacts to user actions goes in an onMounted / event handler on the client. Keep those two apart and the error goes away.

Was this helpful?
Ddmitri

Moved the fetch into useAsyncData and left the click tracking in the handler. Error gone, and the hero is server-rendered now. Thank you both.

Still have questions?