-
Notifications
You must be signed in to change notification settings - Fork 29.6k
Description
Feature request
Is your feature request related to a problem? Please describe.
Let's say I have a hypothetical Analytics.js
module which works differently depending on whether we are on the server or in the browser. It dynamically loads a library-node
or library-browser
package with an eval for example.
Since it's an analytics module we need it inside most of our components to send events.
I tried to initialise it in getInitialProps like this:
static async getInitialProps({req}) => {
this.analytics = new Analytics(!!req)
}
This allows to correctly load Analytics with server or client side setup, but when loaded on the server side, the code will then be sent to the browser, which will error on unknown code (such as fs
etc).
Describe the solution you'd like
It would be nice to have a way to say "here is some code I want ran only on the server because it will break in the browser".
We can already do this with browser code, because we have componentDidMount
which is only called in the browser, so we know it will never get evaluated on the server. Something similar for server-side would be helpful.
Describe alternatives you've considered
Right now I'm just loader my module inside component in componentDidMount
(only in the browser) and abstracted the analytics logic in other non-components modules that are ran in the server, but it's not as flexible and mixes concerns.
Additional context
n/a
Thanks!