Search code examples
reactjsnewrelicisomorphic-javascript

Executing code on server only


I have an Isomorphic ReactJS app. I have a small bit of JS that is used for monitoring only (provided by new relic), that I would like to place within a React component (To be precise this is a component that displays an image or if there is no image available, displays a NoImage component, I want to use the monitoring to track when the no image is loaded.), but the catch is I would only like this JS code to run when rendered on the server and not the client.

Is there a way to achieve this?


Solution

  • When doing server-side rendering you can use componentWillMount() as that is called on the server (in addition to client), whereas componetDidMount() is only called client side. Something like this should work:

    componentWillMount() {
      if (typeof process != 'undefined') {
        executeCodeOnServer()
      }
      // or...
      if (typeof document == 'undefined') {
        executeCodeOnServer()
      }
    }