next.js: Server-side only method to ensure server-only code is never sent to the browser

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!

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 20
  • Comments: 25 (10 by maintainers)

Commits related to this issue

Most upvoted comments

For anyone else like me that comes across this thread wondering what they should use, according to this PR https://github.com/zeit/next.js/pull/7651 process.browser is now deprecated and the recommended approach is

typeof window === "undefined"

I found an interesting solution:

  1. serve next using an express server as shown here
  2. require whatever server side modules you need inside your server.js and add them to the req via an express middleware
const myModule = require('this-only-works-on-the-server');

// ... initialize express + next

server.use((req, res, next) => {
  // now I can access this module inside the getInitialProps function
  req.myModule = myModule;
  return next();
})

server.get('*', (req, res) => {
  return handle(req, res);
})

☝️ this avoids webpack ever trying to include the server side module since the server.js file is never imported by webpack.

👆 the above actually results in the code being removed from your client-side bundles.

We have a test to ensure server-only code does not appear in the client bundle: https://github.com/zeit/next.js/pull/8361!

process.browser as far as I remember is something from webpack and not safe to use. Using typeof window === 'undefined' will give you the same result.

can’t you move your server logic to the server.js file instead of your component?

Did you try?

if (!process.browser) {
  console.log('this code will only run on the server')
}

or

let myLib
if (process.browser) {
  myLib = require('library-browser')
} else {
  myLib = require('library-node')
}

The idea in https://github.com/zeit/next.js/issues/5354#issuecomment-455900041 might be ok within a project, but is not particularly viable for published packages as consumers might not have a custom server setup.

For next-graphql-react I ended up exporting a Next.js plugin that for the client bundle aliases all the server only exports to empty named exports; see withGraphQLConfig.

I also use the undocumented, but handy, process.browser to eliminate client/server code in the relevant bundles: https://github.com/jaydenseric/next-graphql-react/blob/v2.0.0/src/universal/withGraphQLApp.mjs#L85

This used to be inferior to typeof window !== 'undefined' checks as Webpack would include a massive process polyfill, but I’m pretty sure that no longer happens in recent Next.js releases.

I found an interesting solution:

  1. serve next using an express server as shown here
  2. require whatever server side modules you need inside your server.js and add them to the req via an express middleware
const myModule = require('this-only-works-on-the-server');

// ... initialize express + next

server.use((req, res, next) => {
  // now I can access this module inside the getInitialProps function
  req.myModule = myModule;
  return next();
})

server.get('*', (req, res) => {
  return handle(req, res);
})

☝️ this avoids webpack ever trying to include the server side module since the server.js file is never imported by webpack.

That’s a great idea!!

@HaNdTriX really knows what he’s talking about. #5159 added code elimination on webpack-level when process.browser is referenced. Webpack replaces it with true in client build stage, and with false when compiling server. Then it’s just standard dead code elimination routine… This should probably be documented somewhere, but either way maybe we should close this issue?

@pengshaosu :

typeof window === 'undefined'

It specifically replaces typeof window with 'object' or 'undefined' based on the environment. This is then shaken away by Terser because it becomes if(true) or if(false). So yes you have to use the explicit typeof check instead of creating a function for it.

@HaNdTriX being able to check if I’m in the server or the browser is not really a problem. As you mention we can use process.browser or as sergiodxa mentions check for window.

My issue is that if I do something like this.analytics = new mylib(), when the component is rendered server side, the server version of the lib is correctly loaded, and sent to the browser with it, so then the browser has issues with it.

What I’m offering here is a way to mark code to be loaded/ran during server side rendering, but then maybe purged before it is sent to the browser.

The more I try to explain this is less it seems plausible tho 🤔

next-code-elimination only shows how the elimination of getServerSideProps/getStaticProps works and doesn’t include the other Babel plugin optimizations we run including the one that optimizes typeof window. In your example the code would become return true in the compiled output for the browser bundles and return false in the Node.js bundles

I really hate this answer… no offense!

Not sure what your problem is with the answer… I’ve explained the behavior that has been there since Next.js 9.1 or so. Hate is a pretty strong word 😅

It shouldn’t evaluate a function at build time like that without an explicit plugin.

It’s not evaluating a function, it’s converting a statement that is known to always be a certain value because we take care of the full environment.

If this is in fact what’s happening, then we should look into removing webpack all together in favor of pure es6 modules.

This is a bundle size / performance optimizations that so far has had no issues reported by issuers. It only runs against first-party code so not against node_modules (would have even bigger size wins if we did run it against node_modules however that gave issues with some packages in the ecosystem).

Is it possible to prevent this or do somewhat of the reverse: use a plugin to swap a placeholder with hasWindow() to be evaluated at runtime?

Why do you want to do that? There is no benefit to it as we know it’s always going to be defined client-side.

This is no different than process.env.NODE_ENV being replaced with production or development based on the environment.

We do tons of optimizations against first-party code that make sure the bundle output is as optimized as possible. E.g. getStaticProps and getServerSideProps are dropped from client-side bundles as well: https://next-code-elimination.now.sh/

It specifically replaces typeof window with 'object' or 'undefined' based on the environment. This is then shaken away by Terser because it becomes if(true) or if(false). So yes you have to use the explicit typeof check instead of creating a function for it.

I really hate this answer… no offense! It shouldn’t evaluate a function at build time like that without an explicit plugin. If this is in fact what’s happening, then we should look into removing webpack all together in favor of pure es6 modules.

Is it possible to prevent this or do somewhat of the reverse: use a plugin to swap a placeholder with hasWindow() to be evaluated at runtime?