Tuesday, March 1, 2022

ssr - window.location.href with Gatsby Server Side Rendering can be dangerous!

For work I was asked to make a component with a "copy current page URL into clipboard" share button. (if they didn't pass in 'copyText' explicitly because they wanted other information there....)

My first pass had 

  const textToCopy = copyText ?  copyText : window?.location?.href;

above, and 
<button aria-label='copy' onClick={()=>navigator.clipboard.writeText(textToCopy);}>
    Caption
</button>

below. One coworker pointed out that might blow up if the component is rendered serverside, even with the ? marks, just talking about "window" might be an issue . So I change that line to 

  const textToCopy = copyText ?  copyText : ((typeof window !== 'undefined' && window?.location?.href) || '');

but I realized that might not blow up but, since it happened before the render, maybe on SSR it would try and (safely) fail to look up the location, get the blank, and then render an onClick that just copied the blank in.

I think it's safer to make sure all the dynamic work happens in whatever function the onClick calls, so I ended up with


// we make sure the window.location lookup happens onClick, so we don't get caught on the SSR...
const copyTextOrLocation = (copyText: string | undefined) => {
  const textToCopy = copyText ?  copyText : ((typeof window !== 'undefined' && window?.location?.href) || '');
  navigator.clipboard.writeText(textToCopy);
}

and then
<button aria-label='copy' onClick={()=> copyTextOrLocation(copyText)}>
    Caption
</button>

No comments:

Post a Comment