Create New Express.js Apps in Minutes with Express Generator

Share this article

Create New Express.js Apps in Minutes with Express Generator

Express.js is a Node.js web framework that has gained immense popularity due to its simplicity. It has easy-to-use routing and simple support for view engines, putting it far ahead of the basic Node HTTP server.

However, starting a new Express application requires a certain amount of boilerplate code: starting a new server instance, configuring a view engine, and setting up error handling.

Although there are various starter projects and boilerplates available, Express has its own command-line tool that makes it easy to start new apps, called the express-generator.

What is Express?

Express has a lot of features built in, and a lot more features you can get from other packages that integrate seamlessly, but there are three main things it does for you out of the box:

  1. Routing. This is how /home /blog and /about all give you different pages. Express makes it easy for you to modularize this code by allowing you to put different routes in different files.
  2. Middleware. If you’re new to the term, basically middleware is “software glue”. It accesses requests before your routes get them, allowing them to handle hard-to-do stuff like cookie parsing, file uploads, errors, and more.
  3. Views. Views are how HTML pages are rendered with custom content. You pass in the data you want to be rendered and Express will render it with your given view engine.

Getting Started

The first thing you’ll need is to get Node and npm installed on your machine. To do this, either head to the official Node download page and grab the correct binaries for your system, or use a version manager such as nvm. We cover installing Node using a version manager in our quick tip, “Install Multiple Versions of Node.js Using nvm”.

Starting a new project with the Express generator is as simple as running a few commands:

npm install express-generator -g

This installs the Express generator as a global package, allowing you to run the express command in your terminal:

express myapp

This creates a new Express project called myapp, which is then placed inside of the myapp directory:

cd myapp

If you’re unfamiliar with terminal commands, this one puts you inside of the myapp directory:

npm install

If you’re unfamiliar with npm, it’s the default Node.js package manager. Running npm install installs all dependencies for the project. By default, the express-generator includes several packages that are commonly used with an Express server.

Options

The generator CLI takes half a dozen arguments, but the two most useful ones are the following:

  • -v . This lets you select a view engine to install. The default is jade. Although this still works, it has been deprecated and you should always specify an alternative engine.
  • -c . By default, the generator creates a very basic CSS file for you, but selecting a CSS engine will configure your new app with middleware to compile any of the above options.

Now that we’ve got our project set up and dependencies installed, we can start the new server by running the following:

npm start

Then browse to http://localhost:3000 in your browser.

Application Structure

The generated Express application starts off with four folders.

bin

The bin folder contains the executable file that starts your app. It starts the server (on port 3000, if no alternative is supplied) and sets up some basic error handling. You don’t really need to worry about this file, because npm start will run it for you.

public

The public folder is one of the important ones: ​everything​ in this folder is accessible to people connecting to your application. In this folder, you’ll put JavaScript, CSS, images, and other assets that people need when they load your website.

routes

The routes folder is where you’ll put your router files. The generator creates two files, index.js and users.js, which serve as examples of how to separate out your application’s route configuration.

Usually, you’ll have a different file here for each major route on your website. So you might have files called blog.js, home.js, and/or about.js in this folder.

views

The views folder is where you have the files used by your templating engine. The generator will configure Express to look in here for a matching view when you call the render method.

Outside of these folders, there’s one file that you should know well.

app.js

The app.js file is special, because it sets up your Express application and glues all of the different parts together. Let’s walk through what it does. Here’s how the file starts:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

These first six lines of the file are required. If you’re new to Node, be sure to read “Understanding module.exports and exports in Node.js”.

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

The next two lines of code require the different route files that the Express generator sets up by default: routes and users.

var app = express();

After that, we create a new app by calling express(). The app variable contains all of the settings and routes for your application. This object glues together your application.

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

Once the app instance is created, the templating engine is set up for rendering views. This is where you’d change the path to your view files if necessary.

After this, you’ll see Express being configured to use middleware. The generator installs several common pieces of middleware that you’re likely to use in a web application:

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
  • logger. When you run your app, you might notice that all the routes that are requested are logged to the console. If you want to disable this, you can just comment out this middleware.
  • express.json. You might notice that there are two lines for parsing the body of incoming HTTP requests. The first line handles when JSON is sent via a POST request and it puts this data in request.body.
  • express.urlencoded. The second line parses query string data in the URL (e.g. /profile?id=5) and puts this in request.query.
  • cookieParser. This takes all the cookies the client sends and puts them in request.cookies. It also allows you to modify them before sending them back to the client, by changing response.cookies.
  • express.static. This middleware serves static assets from your public folder. If you wanted to rename or move the public folder, you can change the path here.

Next up is the routing:

app.use('/', indexRouter);
app.use('/users', usersRouter);

Here, the example route files that were required are attached to our app. If you need to add additional routes, you’d do it here.

All the code after this is used for error handling. You usually won’t have to modify this code unless you want to change the way Express handles errors. By default, it’s set up to show the error that occurred in the route when you’re in development mode.

Bootstrapping a New Project

Let’s apply what we’ve learned so far to kick-start a basic Express.js application.

Assuming you’ve already installed express-generator as a global module, run the following command to create a new skeleton project:

express -v hbs signup-form

As I mentioned earlier, it’s a good idea to opt for something other than the default (Jade) templating library. Here I’ve gone with Handlebars.js, as I find the mustache-like syntax easy to read and work with.

Once the generator has run, switch into the newly created folder and install the dependencies:

cd signup-form
npm i

At this point, you may notice several warnings about package vulnerabilities. Let’s update the version of Handlebars.js to fix those:

npm install hbs@4.1.0

Now that the project dependencies are installed and updated, let’s customize some of the boilerplate view templates.

The generator creates a layout template which is used to render all the markup that’s shared between views. Open up views/layout.hbs and replace the content with the following:

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">

  <title>{{title}}</title>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
    integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

  <!-- Custom styles for this template -->
  <link href="/stylesheets/style.css" rel="stylesheet">
</head>

<body>
  {{{body}}}
</body>

</html>

The markup here is adapted from an example shown on the Bootstrap website. We also need to add some custom styles, so open up public/stylesheets/style.css and paste in the following:

html,
body {
  height: 100%;
}

body {
  display: -ms-flexbox;
  display: flex;
  -ms-flex-align: center;
  align-items: center;
  padding-top: 40px;
  padding-bottom: 40px;
  background-color: #f5f5f5;
}

.full-width {
  width: 100%;
  padding: 15px;
  margin: auto;
}

.form-signin {
  max-width: 330px;
}
.form-signin .checkbox {
  font-weight: 400;
}
.form-signin .form-control {
  position: relative;
  box-sizing: border-box;
  height: auto;
  padding: 10px;
  font-size: 16px;
}
.form-signin .form-control:focus {
  z-index: 2;
}
.form-signin input {
  border-radius: 0;
  margin-bottom: -1px;
}
.form-signin input:first-of-type {
  border-top-left-radius: 0.25rem;
  border-top-right-radius: 0.25rem;
}
.form-signin input:last-of-type {
  border-bottom-left-radius: 0.25rem;
  border-bottom-right-radius: 0.25rem;
  margin-bottom: 10px;
}

Now that we’ve customized the layout, let’s add the markup for the home page. Open views/index.hbs and replace the contents with the following:

<form action="/subscribe" method="POST" class="form-signin full-width text-center">
  <h1 class="h3 mb-3 font-weight-normal">Join the mailing list</h1>
  <label for="name" class="sr-only">First name</label>
  <input type="text" name="name" class="form-control" placeholder="First name" required autofocus>
  <label for="email" class="sr-only">Email</label>
  <input type="email" name="email" class="form-control" placeholder="Your email" required>
  <label for="emailConfirmation" class="sr-only">Email (confirm)</label>
  <input type="email" name="emailConfirmation" class="form-control" placeholder="Your email (confirm)" required>
  <button class="btn btn-lg btn-primary btn-block" type="submit">Subscribe</button>
  <p class="mt-5 mb-3 text-muted">&copy; 2020</p>
</form>

This will display a newsletter signup form on our home page.

Let’s add a route our form can be submitted to, where we can access the form data and do something with it. Open up the file routes/index.js and add the following route beneath the home-page route:

router.post("/subscribe", function(req, res, next) {
  const { name, email } = req.body;

  // 1. Validate the user data
  // 2. Subscribe the user to the mailing list
  // 3. Send a confirmation email

  res.render("subscribed", {
    title: "You are subscribed",
    name,
    email
  });
});

In the route handler, we’ve extracted the form data from the request object. After processing the signup (shown as pseudo-code), we pass the data through to our subscribed view.

Note: if you want to learn more about working with forms in Node, read “Forms, File Uploads and Security with Node.js and Express”.

Let’s create that now, by opening a new file, views/subscribed.hbs, and adding the following markup:

<div class="full-width text-center">
  <h1 class="display-3">Thank You, {{name}}!</h1>
  <p class="lead"><strong>Please check your email</strong> to confirm your subscription to our newsletter.</p>
  <hr>
  <p>
      Having trouble? <a href="">Contact us</a>
  </p>
  <p class="lead">
      <a class="btn btn-primary btn-sm" href="/" role="button">Continue to homepage</a>
  </p>
</div>

To give our new site a try, fire it up by running npm run start in the project folder, and visit http://localhost:3000.

And here’s the demo running on CodeSandbox.

A Useful Tool

Hopefully you now have a clear idea of how the express-generator tool can save you time writing repetitive boilerplate when starting new Express-based projects.

By providing a sensible default file structure, and installing and wiring up commonly needed middleware, the generator creates a solid foundation for new applications with just a couple of commands.

FAQs About Creating Apps with Express Generator

What is Express Generator?

The Express Generator, also known as “Express Generator” or “Express Application Generator,” is a command-line tool designed to accelerate the creation of web applications using the Express.js framework within Node.js. It streamlines the initial setup process by generating a project structure, including folders, files, and basic configurations, that align with best practices for Express.js development. This tool is particularly valuable for developers as it expedites project initialization and provides a solid foundation for building web applications or APIs with Express.js.
To use the Express Generator, you first need to install it globally using npm. Once installed, you can create a new Express.js project by running the express command followed by your chosen project name. This generates the essential files and directories, including routing, middleware setup, view engine configuration, and more, allowing you to focus on building your application’s unique functionality. The generated structure serves as a starting point that developers can customize and expand upon according to their specific project requirements. Overall, the Express Generator is a time-saving tool that simplifies the initial stages of Express.js web application development.

What does NPX Express Generator do?

npx express-generator is a command-line command that facilitates the use of the Express Generator tool without requiring a global installation. npx is a utility that comes bundled with npm (Node Package Manager) and allows you to execute packages directly from the npm registry without the need for a permanent global installation.
When you invoke npx express-generator, it fetches the latest version of the Express Generator from the npm registry and runs it. The Express Generator simplifies the process of initializing an Express.js application by creating a project structure with directories, files, and default configurations. This quick-start tool aids developers in launching Express.js projects efficiently.
Using npx with express-generator is a convenient approach for starting Express.js projects without the need to install the generator globally. It ensures that you’re working with the most up-to-date version available on the npm registry, making it especially handy for occasional project creation or when you prefer to use different generator versions for various projects.

Is Express.js still used?

Express.js (also known as Express) is still widely used and remains a popular choice for building web applications and APIs in Node.js. It has a large and active developer community, and many production applications have been built using Express.js.

How to create an Express project?

To create an Express.js project quickly, you can use the Express Generator, which streamlines the initial setup. First, you’ll want to ensure that Express Generator is installed on your system. If it’s not already installed, you can do so globally using npm with the command npm install -g express-generator.
Next, you can generate a new Express.js project by executing the express command followed by your chosen project name. For example, running express my-express-app will create a project named “my-express-app.” This command automatically sets up the necessary directory structure, default files, and basic configurations.
Once the project is generated, navigate to the newly created project directory using cd my-express-app. Here, you can install the project’s dependencies by running npm install.
To start your Express.js application, use the npm start command. By default, the application runs on port 3000, and you can access it in a web browser at http://localhost:3000. The Express Generator simplifies the initial setup, providing a structured and efficient way to kickstart your Express.js project, allowing you to focus on building your application’s specific functionality.

What is the difference between Express and Express Generator?

Express and Express Generator are both tools used in the context of web application development with the Express.js framework in Node.js, but they serve distinct purposes.
Express is the core web application framework. It offers a powerful set of features and functionalities for building web applications and APIs. When you choose Express, you start with a minimal project structure and have the flexibility to define the project’s architecture, including routes, middleware, views, and more. Express gives you complete control over your project’s structure, making it suitable for a wide range of applications, from small APIs to complex web applications.
Express Generator, on the other hand, is a command-line tool provided by the Express.js team. It simplifies the initial setup of an Express.js project by generating a predefined directory structure, default files, and basic configurations. Express Generator is designed to save time during project setup, providing a standardized starting point that developers can build upon. It’s particularly useful when you want to get a new Express.js project up and running quickly, as it streamlines the initial setup process and helps you avoid repetitive boilerplate code.

Paul SauvePaul Sauve
View Author

Paul writes code for the DOM and codes not for the DOM. He blogs at burngames.net also runs @JoinDevathon.

Expressexpress generatornodenode-hubNode-JS-Tools
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week