02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Setting up hot refresh middleware

Understanding Node.js Module Exports for Production and Development

When developing Node.js applications, effectively managing environments is critical to maintain code clarity and ensure optimal performance. In this tutorial, you’ll learn how to use the CommonJS module system to create reusable server modules, distinguishing between production and development environments.


What Are Node.js Module Exports?

In Node.js, the CommonJS module system is used to manage imports and exports between files. Using require to import modules and module.exports to export them is a foundational practice. This allows you to separate concerns and structure your application logically.

For instance, instead of hardcoding configurations, you can create a build function that initializes your server with specific parameters like port numbers. This modular approach enhances maintainability and reusability.


Creating a Production Server Module

Here’s how to build a simple production server module:

  1. Define Your Build Function:

    • Move server configuration logic into a build function that accepts parameters like port.
    • Ensure your server only initializes when the build function is invoked.
    module.exports = {
        build: (port) => {
            const express = require('express');
            const app = express();
    
            // Add middleware or routes here
            app.use(express.static('public'));
    
            // Start the server
            app.listen(port, () => console.log(`Server running on port ${port}`));
    
            return app;
        }
    };
    
  2. Create a Production Server File:

    • Import the module and invoke the build function with your desired port number.
    const server = require('./source/server');
    server.build(3000);
    
  3. Separate Development Logic:

    • You can apply similar logic to a server.dev.js file for development-specific needs, such as enabling hot reloading or detailed logging.

Why Separate Production and Development?

Separating these environments ensures:

  • Security: Production servers avoid exposing debugging tools or unnecessary logs.
  • Efficiency: Optimized builds focus on performance, while development builds prioritize flexibility and feedback.
  • Maintainability: Cleaner, environment-specific configurations simplify debugging and deployment.

Practical Example in a React-Node Environment

This modular approach is particularly valuable when working with tools like Webpack or Babel for server-side rendering (SSR). By isolating server logic, you can ensure production builds prioritize performance while still enabling efficient development workflows.

For example:

  • Production builds might pre-render React components.
  • Development builds could include hot module replacement (HMR).

Conclusion

By using Node.js module exports, you can modularize your application, cleanly separate environments, and build scalable server-side applications. This approach is a cornerstone of modern JavaScript development, and mastering it will enhance your ability to manage complex projects efficiently.

For more advanced techniques, explore the rest of this course on server-side React performance optimization.
👉 Full course available here

2024

The approach described for using CommonJS and creating modularized server setups is still valid in 2024, but it may not be the most optimal or modern approach. Here's a breakdown of why and what adjustments can be made to align with current best practices:


1. CommonJS vs. ES Modules (ESM)

  • Current Practice: CommonJS (require and module.exports) was the standard for many years, but as of Node.js 14 (LTS) and later, ES Modules (ESM) have become fully supported and are now the recommended standard for modern JavaScript.
  • Optimal Practice for 2024:
    • Use ES Modules (import and export) for cleaner syntax and better compatibility with modern JavaScript tools like Webpack, Vite, and Rollup.
    • Example of a server module using ESM:
      export const build = (port) => {
          const express = require('express');
          const app = express();
      
          app.use(express.static('public'));
      
          app.listen(port, () => console.log(`Server running on port ${port}`));
          return app;
      };
      
      And in your production server file:
      import { build } from './source/server.js';
      build(3000);
      

2. Environment-Specific Configurations

  • Current Practice: Separate development and production servers using require-based logic.
  • Optimal Practice for 2024:
    • Use environment variables and configuration management libraries like dotenv or frameworks with built-in environment handling like Next.js.
    • Example with dotenv:
      import { config } from 'dotenv';
      config();
      
      const build = (port) => {
          const express = require('express');
          const app = express();
      
          const environment = process.env.NODE_ENV || 'development';
          console.log(`Running in ${environment} mode`);
      
          app.use(express.static('public'));
          app.listen(port, () => console.log(`Server running on port ${port}`));
      
          return app;
      };
      
      build(process.env.PORT || 3000);
      

3. Considerations for Production-Ready Deployments

  • Current Practice: Directly manage the server logic within Node.js.
  • Optimal Practice for 2024:
    • Use containerized environments with Docker or serverless platforms like Vercel or AWS Lambda for better scalability and simpler deployment.
    • Integrate tools like PM2 for process management in traditional setups to handle server clustering and restart on failure.

4. Framework-Based Alternatives

  • Next.js:

    • If the goal is server-side rendering (SSR) or building universal JavaScript applications, Next.js is the go-to solution in 2024.
    • It abstracts much of the server setup process, provides built-in handling for SSR and static site generation (SSG), and offers seamless production-ready configurations.
  • Express Alternatives:

    • For microservices or APIs, consider lightweight frameworks like Fastify, which offers better performance and a modern developer experience compared to Express.

5. Performance Optimizations

  • Current Practice: Cache files and pre-render data manually.
  • Optimal Practice for 2024:
    • Utilize built-in caching mechanisms provided by frameworks or reverse proxies like NGINX or Varnish.
    • Use Content Delivery Networks (CDNs) like Cloudflare or AWS CloudFront to offload static content delivery.

6. TypeScript Support

  • Modern JavaScript projects increasingly adopt TypeScript for improved type safety and developer productivity.
  • Example:
    import express, { Application } from 'express';
    
    export const build = (port: number): Application => {
        const app: Application = express();
        app.use(express.static('public'));
    
        app.listen(port, () => console.log(`Server running on port ${port}`));
        return app;
    };
    

Conclusion

While the traditional CommonJS-based modular server setup is still functional, in 2024, you should aim to:

  • Transition to ES Modules.
  • Use environment management tools like dotenv.
  • Adopt Next.js or other modern frameworks for React SSR projects.
  • Leverage containerization, serverless platforms, or modern deployment techniques for scalability.

This ensures your project is aligned with the latest tools, practices, and performance optimizations.

Video Transcript

00:00All righty, let's get this party started.
00:03Our last section is gonna be focused on how
00:05to package things up with Webpac.
00:08Well natively, a lot
00:09of times people use the default settings
00:11that are just not right for production.
00:13So now that we're creating a production environment
00:16settings, we really need
00:17to oso set up our development environment.
00:20And to do that, we're gonna take a look at the different
00:22middlewares that we could use to set up
00:24and configure Webpac to work.
00:25Just like the default web packaging worked only now
00:28with our complete control over all the other settings
00:31that we've done in the previous section.
00:33So we're gonna use middlewares for that
00:35and we're gonna get it to run our real server
00:38with those middlewares.
00:40We're gonna optimize CSS for production,
00:42we're gonna optimize JavaScript for production,
00:45and we're also gonna cache
00:46and compress all of our assets to make sure
00:49that our files will be served in the most optimized
00:52way to users.
00:53And in this selection, we're gonna go ahead
00:55and start setting up hot refresh middleware.
00:58Really what we're gonna do is we're gonna start
01:01com connecting our web pack into our
01:04development environment.
01:05So we're gonna create the packaging ourselves.
01:08It's gonna take us two steps.
01:10Starting off with this lecture,
01:11we're gonna integrate web pack into the server.
01:15Alright, in our last session we had a,
01:17a small little mistake that I did not notice, uh,
01:20while recording, but make sure that your server,
01:22your we're sending in our purchase as a reminder,
01:25we have our production environment
01:27and we're sending in a port.
01:28I forgot to actually send it in.
01:30So although we're sending it in
01:32and the server itself, I didn't actually use it.
01:34So make sure that you're actually sending it in to listen
01:37and not hard coding a port id.
01:39And that's gonna become relevant now when we're starting
01:41to work on the dev environment
01:43because in the dev environment,
01:44I've duplicated the exact same code
01:46that was in the production environment,
01:48but instead I changed it to 3010 Now just
01:52to show the difference between the two.
01:54Now w with that said,
01:55our server right now is not gonna be good enough if we just
01:58run it this way, nor would it be good enough if we ran our
02:02server using the start, using the Webpac dev server.
02:05Our problem with using the Webpac dev server is the Webpac
02:09dev server doesn't have our express server
02:12that we created throughout the last section.
02:15So what we really need
02:17to happen is we want our webpac dev server,
02:19or really we want our development environment to have access
02:22to our server that we've just created
02:24and the reason why we've created
02:25that whole workaround in the last lecture.
02:28So to be able to do that, I'm gonna need
02:30to install a few packages and I'm gonna go ahead
02:33and do that, and then we'll continue in the
02:35build process itself.
02:36So go and install NPM install.
02:42By the way, if you're asking yourself why save
02:44dev, why not just save?
02:46Well save is for the production.
02:48Does the production itself,
02:49when the server is actually running,
02:51does it need these packages that we're gonna install?
02:53The answer is no. Or in other words,
02:56whenever our production is
02:58Running, we're gonna do the web pack separately than we're
03:01actually doing the server itself.
03:03While it's true, when we're gonna do our non-production,
03:06our dev environment, we are going to use those packages,
03:09and that is the reason why we're gonna go ahead
03:11and save it to Dev and not just save.
03:14Okay? So the two packages that we want is the web pack
03:18dev middleware,
03:20and that is gonna help us add a middleware for express
03:23to enable us to have access
03:25to the web pack development environment.
03:27And we're also gonna have a web pack, web pack, web pack,
03:32hot middleware.
03:35Okay? So those are two extra add-ons
03:38that we're gonna put onto our express server.
03:40That one of them is gonna give us access
03:41to the development environment
03:43and the other will enable us to have hot refreshes.
03:46Okay, so let's go ahead and while it's
03:48installing, let's set it up.
03:49So I'm gonna go into our development environment,
03:52and the first thing that I'm gonna do is I'm gonna go ahead
03:54and I'm gonna create a constant for our web pack,
03:57and I'm just gonna require it.
04:00Now, the next thing I'm gonna require is our config file.
04:03This time around, it's not happening automatically,
04:05but I need to load up that web pack dot config.
04:08So I'm gonna go ahead and I'm gonna call it config
04:10and I'm gonna require it.
04:12And because we're working inside of Node,
04:13it will automatically take this JSON
04:16and just convert it into a standard JavaScript object.
04:19So it's inside of this current folder, web pack, do config,
04:24and we don't have to type JS
04:26because it's a given in node js.
04:28Beautiful. Now, there's a couple of things that we wanna do
04:32to our application,
04:34and the first among them is we want to go ahead
04:37and add into our,
04:39what I really wanna do is I wanna basically add in a
04:42few more plugins.
04:43And these plugins are only gonna be available in the,
04:45in the development, not the production.
04:47So I'm gonna go ahead and add those right here.
04:50Even before we use the config,
04:52I'm just gonna basically push those plugins.
04:56Now I'm assuming that there are plugins already.
04:58So, you know, in a real world environment,
05:00you might wanna do this a little bit differently
05:02or create two separate config files, a config file
05:05for production and a config file for development,
05:09which is probably a better idea.
05:10But this is just another interesting idea
05:12of how to set this up.
05:13So on shift, I'm gonna push into our, um,
05:17config to its plugins.
05:19We're gonna push in three new plugins.
05:23We're gonna get them from webpac as well.
05:25And I'm gonna ask for the hot module
05:30replacement plugin.
05:32Lemme just double check that I typed that correctly.
05:35Let me just copy paste because this is a big word.
05:37Yeah, that's all good. So that's the first plugin.
05:40Now, what does this plugin do?
05:42Well, the hot module replacement plugin enables us
05:45to replace content hot as the name implies.
05:49Now we have to also enable it within the application,
05:52our client application itself,
05:54which we'll do that momentarily. Okay, so that's the first
05:56Plugin, right? So the
05:57next item that we're gonna do is we're gonna set up
06:00our new web pack
06:03no errors plugin.
06:06Now what that will do is it's gonna make sure
06:08that if we have any errors, that it will, oh, not three Rs,
06:12but just two, it will make sure
06:14that these errors will not break our packaging.
06:17Okay. So with that said, let's go ahead
06:19and use these two first, and we'll look
06:21at the third one in a minute.
06:22And what I wanna do now that I've set this up is I wanna run
06:26and test it out and see if everything is still working,
06:28but technically it won't yet work
06:30because there's a few more things that we have to do
06:33for one, hot refreshes are not gonna happen automatically.
06:37They could only happen if our client itself
06:40or whoever it's actually listening to.
06:42So in our case, when we take a look at our web pack,
06:45we'll see that our client, yes,
06:46or any of its subsidiary children, needs
06:48to basically have access to be able to be refreshed.
06:52Now, as as we were saying that in our, uh,
06:55development environment,
06:56we've added this hot model replacement, what I really need
06:59to do is I just deleted some of those extra lines there.
07:02I'm just gonna go ahead into the bottom
07:03of my, of my code here.
07:04It doesn't really matter where,
07:06but I'm gonna go to the bottom.
07:07And what I want do is I want
07:08to basically just add into my code, something very simple,
07:11and I'm gonna ask, and by the way,
07:13this is gonna be removed when it's
07:14being packaged by web pack.
07:16So a module hot,
07:18especially when we're gonna do it in production.
07:20So module, module hot,
07:24if it exists, then I'm gonna go ahead
07:26and just announce to that item, by the way, um, a accept,
07:31which basically means that it's gonna let us
07:33to refresh the code.
07:34And that's basically what's what is gonna tie the knot
07:38between our development, uh, between our web pack on the,
07:42on the backend as we're building it out
07:43and actually enabling it to hot refresh.
07:45Now we're far from done.
07:47We still need to continue connecting and configuring.
07:49We're just starting
07:50to set up our configuration file in this lecture.
07:53We integrated Webpac into the server,
07:55and in the next one, we'll continue down the path
07:58of building up our Webpack development server ourselves
08:02using Middlewares.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!