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
- Replace `process.browser` environment check with `window` Next.js has changed the recommended way to detect whether we're on the client or not to check for the presence of `window`. See https://gith... — committed to LBHackney-IT/mat-process-thc by erbridge 7 years ago
- Replace `process.browser` environment check with `window` Next.js has changed the recommended way to detect whether we're on the client or not to check for the presence of `window`. See https://gith... — committed to LBHackney-IT/mat-process-thc by erbridge 7 years ago
- Replace `process.browser` environment check with `window` Next.js has changed the recommended way to detect whether we're on the client or not to check for the presence of `window`. See https://gith... — committed to LBHackney-IT/mat-process-thc by erbridge 7 years ago
- Replace `process.browser` environment check with `window` Next.js has changed the recommended way to detect whether we're on the client or not to check for the presence of `window`. See https://gith... — committed to LBHackney-IT/mat-process-thc by erbridge 7 years ago
- Replace `process.browser` environment check with `window` Next.js has changed the recommended way to detect whether we're on the client or not to check for the presence of `window`. See https://gith... — committed to LBHackney-IT/mat-process-thc by erbridge 7 years ago
- Replace `process.browser` environment check with `window` Next.js has changed the recommended way to detect whether we're on the client or not to check for the presence of `window`. See https://gith... — committed to LBHackney-IT/mat-process-thc by erbridge 7 years ago
- Replace `process.browser` environment check with `window` Next.js has changed the recommended way to detect whether we're on the client or not to check for the presence of `window`. See https://gith... — committed to LBHackney-IT/mat-process-thc by erbridge 7 years ago
- Replace `process.browser` environment check with `window` Next.js has changed the recommended way to detect whether we're on the client or not to check for the presence of `window`. See https://gith... — committed to LBHackney-IT/mat-process-thc by erbridge 7 years ago
- Replace `process.browser` environment check with `window` Next.js has changed the recommended way to detect whether we're on the client or not to check for the presence of `window`. See https://gith... — committed to LBHackney-IT/mat-process-thc by erbridge 7 years ago
- Replace `process.browser` environment check with `window` Next.js has changed the recommended way to detect whether we're on the client or not to check for the presence of `window`. See https://gith... — committed to LBHackney-IT/mat-process-thc by erbridge 7 years ago
- Update ThemeContext.tsx useEffect only runs on client, i think you do not need to check for process.browser. Also, `process.browser` is deprecated in favor of `typeof window === 'undefined'` (https:/... — committed to jose-donato/nikitarudenko.dev by jose-donato 6 years ago
- Update ThemeContext.tsx useEffect only runs on client, i think you do not need to check for process.browser. Also, `process.browser` is deprecated in favor of `typeof window === 'undefined'` (https:/... — committed to jose-donato/nikitarudenko.dev by jose-donato 6 years ago
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.browseris now deprecated and the recommended approach isI found an interesting solution:
server.jsand add them to thereqvia an express middleware☝️ this avoids webpack ever trying to include the server side module since the
server.jsfile 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.browseras far as I remember is something from webpack and not safe to use. Usingtypeof 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?
or
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-reactI ended up exporting a Next.js plugin that for the client bundle aliases all the server only exports to empty named exports; seewithGraphQLConfig.I also use the undocumented, but handy,
process.browserto eliminate client/server code in the relevant bundles: https://github.com/jaydenseric/next-graphql-react/blob/v2.0.0/src/universal/withGraphQLApp.mjs#L85This used to be inferior to
typeof window !== 'undefined'checks as Webpack would include a massiveprocesspolyfill, but I’m pretty sure that no longer happens in recent Next.js releases.That’s a great idea!!
@HaNdTriX really knows what he’s talking about. #5159 added code elimination on webpack-level when
process.browseris referenced. Webpack replaces it withtruein client build stage, and withfalsewhen 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 :
It specifically replaces
typeof windowwith'object'or'undefined'based on the environment. This is then shaken away by Terser because it becomesif(true)orif(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 becomereturn truein the compiled output for the browser bundles andreturn falsein the Node.js bundlesNot 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’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.
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).
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_ENVbeing replaced withproductionordevelopmentbased 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.
getStaticPropsandgetServerSidePropsare dropped from client-side bundles as well: https://next-code-elimination.now.sh/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?