6
votes

Let's say I have a file named utils.js, containing two functions s and c. s is a server-side function (Being called on an /api endpoint handler), and uses mongodb package. c is a client-side function (will be bundled and sent to the browser).

When compiling the app using next build, will it cause any issues? Does webpack know to bundle only part of a file/module? (considering server-side functions and imports as a "dead code" since they only being called from a server-side code)

Thanks

2

2 Answers

3
votes

If you need to know which functions get bundled to the client & which ones to the server, there's an easy way to know this → https://next-code-elimination.now.sh/

Just copy & paste the contents of your file into it & you'll see which code gets bundled to the client & which code is bundled to the server. If you have imports then make sure to put all the imports in one file so you can see how it works.

The thumb rule is:

Anything like getServerSideProps, getStaticProps & getStaticPaths will be removed from the bundled code. If you import anything from a file that uses server-side code like fs but doesn't use it in any of the above 3 functions, then it won't be removed (check at Next Code Elimination Tool) & will give you an error.

The tool is the answer. I copy-pasted my file in it & found the answer in an instant.

1
votes

I think there will be errors but not in the build time. It is likely issues will happen in the run time. You won't be able to access file systems on the client side just like how you can't access the window object on the server-side.

In my current project, we have utility functions for both the server-side, client-side, or universal. All server-side functions are called in getServerSideProps to make sure they work as expected. All your server-side code in getServerSideProps will not be imported as part of the client-side bundle if that's what you mean by "dead code". According to the Next.js

Note: You can import modules in top-level scope for use in getServerSideProps. Imports used in getServerSideProps will not be bundled for the client-side.

This means you can write server-side code directly in getServerSideProps. This includes reading from the filesystem or a database.

I'm not aware of a way you can ask webpack to bundle part of the file or execute a subset of import statements.

I hope that provides some help.

Reference:

Docs - getServerSideProps

Custom Webpack Config