Skip to content
Advertisement

Why is my client side code being compiled and ran on node backend?

I’m new to SSR so I’m not sure if this problem and my solution is standard practices but I can’t imagine so.

My goal is to have a dynamic page that allows users to add/remove items on the page. I originally programmed this component with the intention of it only being a client side react project but now I want to put it on a server. Now when I’m translating my code to the new project I’ve run into a couple errors now that has to do with my backend running the code that is only supposed to be run on client side.

For instance I ran into this problem earlier React Redux bundle.js being thrown into request, and I was able to solve this issue with a Janky solution where I make sure that it’s being passed client side code and stop the execution of its being passed from the backend. Now I’ve had to refactor my code to not use the fetch() function because it’s not a function that the node backend recognizes and it’s now complaining about my use of the document object because that’s not a thing in node either.

I can keep on going importing new modules to fix the errors to keep my website from crashing but I feel like I’m on a small boat patching up new holes with duck tape waiting to find the next hole.

Here’s an image of my config if that’s necessary I also have additional images in my previous stack overflow question (link aobove)

enter image description here

Advertisement

Answer

For the bundle.js issue I am not sure to understand why it happens.

For the fetch issue, I think this is a common problem with SSR and if you implement it by yourself you need to handle conditions in different places of your app:

if(!!window) {
  // do client-side stuff like accessing
  // window.document
}

Basically the most common usage of SSR is to handle the first execution of you app on the server side. This include:

  • Route resolution
  • Fetching data (using nodejs http module)
  • Hydrating stores (if you use redux or other data library)
  • rendering UI

Once the execution is done, your server returns the bundled js app with hydrated store and UI and returns it to the client. Subsequent requests or route update will be executed on the client side, so you can directly use fetch or react-router


The pros of doing SSR are:

  • Great first contentful
  • Great for SEO
  • Client-side machine do less works

There is a lot of libraries that can help you with SSR as well as frameworks like nextjs, use-http

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement