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

Time:10-02

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 enter image description here

CodePudding user response:

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

  • Related