Skip to content

Server-side only method to ensure server-only code is never sent to the browser #5354

@Jauny

Description

@Jauny

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions