O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Mastering Web Application Development with Express

Book Description

A comprehensive guide to developing production-ready web applications with Express

In Detail

Prototyping an application is one thing, but making sure it's ready to launch is a whole different story. This book will enable you to create maintainable, high performance, and scalable web applications that will meet your production needs. From getting started to how to develop, hone, and protect your application with Express, this book gives you all the practical information you need to feel truly confident with the advanced features of Express.

The essential bits and pieces of the framework are explained at the beginning, for a better understanding of the strong points of the framework. From there, we'll take you through the development of an application, from using middleware and template engines to RESTful APIs. By the end, you will have mastered the patterns of reusable code and error handling, and will have learned about other important aspects such as debugging, monitoring, and security.

What You Will Learn

  • Understand the inner workings of the middleware system and build your own
  • Harness and customize middleware for your needs
  • Create RESTful APIs using Express
  • Optimize the performance and throughput of Express web applications
  • Gain an insight into avoiding repeatable code and improve developer productivity
  • Secure, debug, and error-handle your application in a live production environment
  • Improve code quality using existing tools

Downloading the example code for this book. You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

Table of Contents

  1. Mastering Web Application Development with Express
    1. Table of Contents
    2. Mastering Web Application Development with Express
    3. Credits
    4. About the Author
    5. About the Reviewers
    6. www.PacktPub.com
      1. Support files, eBooks, discount offers, and more
        1. Why subscribe?
        2. Free access for Packt account holders
    7. Preface
      1. What this book covers
      2. What you need for this book
      3. Who this book is for
      4. Conventions
      5. Reader feedback
      6. Customer support
        1. Downloading the example code
        2. Errata
        3. Piracy
        4. Questions
    8. 1. Diving into Express
      1. The best parts of Express
      2. Comparing Express with other frameworks
        1. Goal
        2. Conventions
        3. Databases
        5. Overall
      3. Use cases
        1. Complex applications with heavy I/O bound operations
        2. Single-page applications
        3. Reusable applications
        4. Code sharing between the server and the client
        5. A base to create more complex frameworks
        6. Bad use cases
      4. Express into the wild
      5. The application structure
        1. Group files by features
        2. Model-View-Controller
          1. Developing a real MVC application
            1. Bootstrapping a folder structure
            2. Installing NPM dependencies
            3. Setting up the configuration file
            4. The starting script
            5. The database library
            6. Routes
            7. Models
              1. The file model
              2. The User model
            9. Running the full application
      6. Summary
    9. 2. Component Modularity Using Middleware
      1. Connecting middleware
      2. The functionality of middleware
        1. Pushing items to an array
        2. Looking at the execution flow using logs
      3. Creating configurable middleware
        1. Closures to the rescue
        2. Caching middleware – a practical example
          1. A first try at the caching middleware
          2. Measuring the performance benefits of the caching middleware
          3. Making the caching middleware configurable
      4. Environment-based loading of middleware
      5. Express routes
        1. Specifying the path
        2. Reusable route handlers
        3. Route wildcards
      6. Ordering of middleware
      7. Handling errors with middleware
      8. Mounting subapplications
      9. Replicating the middleware system
        1. The main file
        2. Handling requests
        3. Demonstrating the application
        4. Adding the routes handler
      10. Summary
    10. 3. Creating RESTful APIs
      1. An overview of REST
        1. HTTP methods (verbs)
        2. HTTP status codes
          1. Successful 2xx
          2. Redirection 3xx
          3. Client error 4xx
          4. Server error 5xx
      2. SmartNotes application requirements
      3. Creating RESTful URLs of the application
      4. Implementing the SmartNotes application
        1. The bootstrapping phase
        2. Dealing with validation
          1. Creating a custom validation module
          2. Improving performance with memoization
        3. Implementing the models
          1. Test helpers
          2. The Note model
          3. The User model
        4. Functional tests and route implementation
          1. User endpoints
          2. Notes endpoints
      5. API versioning
      6. API rate limiting
      7. Throttling
      8. Facilitating caching
      9. Content negotiation
      10. Summary
    11. 4. Leveraging the Power of Template Engines
      1. The different types of template engines
        1. Logic-less template engines
        2. Template engines with logic
        3. Programmatic template engines
      2. View helpers and application-level data
      3. Sharing code between templates with partial views
      4. DRY templates with layouts
      5. Template engine consolidation with consolidate.js
      6. View caching in production
        1. The view cache setting and its effect
        2. Clearing the cache without a restart
      7. Integrating a template engine with Express
      8. Choosing a template engine
      9. Summary
    12. 5. Reusable Patterns for a DRY Code Base
      1. Creating the MovieApp sample application
        1. Application structure and required modules
        2. Creating the server.js file
        3. Creating the route handlers
        4. Doing the heavy lifting inside the model
        5. Wrapping it up
      2. Error checks and callback functions
      3. Tiny modules for better control flow
      4. Ensuring a single callback execution
      5. Extending objects in a reusable way
      6. A simple way to create custom errors
      7. Summary
    13. 6. Error Handling
      1. Runtime (operational) errors and human errors
      2. Ways of delivering errors in the Node applications
        1. Throwing errors in the synchronous style
        2. The error-first callback pattern
        3. The EventEmitter errors
      3. Strings instead of errors as an antipattern
      4. Improving stack traces
      5. Handling uncaught exceptions
      6. Logging errors
      7. Creating a custom Express error handler
      8. Richer errors with VError
      9. Error handling in a practical application
        1. Creating the application entry point
        2. Real-time updates with Primus
        3. Post and User models
        4. About routes
        5. Views and static resources
        6. Running the application
      10. Summary
    14. 7. Improving the Application's Performance
      1. Serving static resources with Express
        1. Using Node modules
          1. The middleware order can impact performance
          2. Asset versioning
          3. Compress and minify
          4. An in-memory static middleware
          5. Using a content delivery network
          6. Using NGiNX
      2. Backend improvements
        1. Avoiding synchronous functions
        2. Doing things in parallel whenever possible
        3. Using streams to process data
        4. Streaming templates with trumpet
        5. Caching dynamic data
          1. ETag for dynamic data
        6. Using a cluster to handle more concurrent connections
        7. HTTPS with Stud
      3. Summary
    15. 8. Monitoring Live Applications
      1. Logging
        1. Bunyan – a battle-tested logger
        2. Redirecting logs to an external service
        3. Things to note
      2. Simple tips for improving the application monitoring
      3. Collecting metrics
        1. Getting the slowest endpoints of the application
        2. Tracking the network traffic
        3. Measuring the average function response time
      4. Useful existing monitoring tools
      5. Ensuring the application uptime
      6. Summary
    16. 9. Debugging
      1. A better error-handling middleware
        1. Application for displaying the time in the current time zone
        2. Adding the improved error handler
      2. Using a debug flag
        1. Debug versus logger
      3. Debugging routes and middleware
      4. Using the V8 debugger
        1. Creating our buggy application
        2. Using Node's debugger client in the terminal
        3. Using node-inspector
      5. Debugging memory leaks
      6. Adding a REPL to our Express application
      7. Removing debugging commands
      8. Summary
    17. 10. Application Security
      1. Running Express applications on privileged ports
        1. Dropping root privileges
        2. Redirecting to another port using iptables
        3. Using authbind
      2. Cross-site request forgery protection
      3. Cross-site scripting
        1. Validating input
        2. Sanitizing output
      4. HTTP security headers with Helmet
      5. Handling file uploads
      6. Session middleware parameters
      7. Reauthenticating the user for sensitive operations
      8. Summary
    18. 11. Testing and Improving Code Quality
      1. The importance of having automated tests
      2. Testing toolbox
        1. Mocha
        2. should.js
        3. Sinon.js
          1. Spies
          2. Stubs
          3. Mocks
        4. Supertest
        5. Proxyquire
        6. Generating phony data using Faker.js
      3. Creating and testing an Express file-sharing application
        1. Running the application
        2. Unit tests
        3. Functional tests
      4. Running tests before committing in Git
      5. Code coverage
      6. Complexity analysis of our code
      7. Code linting
      8. Load testing
      9. Client-side testing
      10. Continuous Integration
        1. CI servers
        2. Free CI for open source projects
      11. Summary
    19. Index