Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 43 ยท Getting Started

The Express Generator and Project Scaffolding

See what npx express-generator creates, read the generated app.js, bin/www and folders, then modernize it for Express 5 and ES modules or skip it with a manual setup.

Starting a new project always begins with the same chores: create a folder, run npm init, install Express, make an entry file, decide where routes and views go. Express has an official tool that does this in one command, the application generator, express-generator. It is how many tutorials, bootcamps and older company codebases start, so you will certainly meet projects that came out of it.

This lesson shows what the generator creates and why, explains the pieces of the generated code, points out what is dated about it, and compares it with a hand-made setup. You cannot install or run npm packages on this site, so the generator itself is read-only here. The runnable examples re-create the ideas behind the generated files so you can see them work.

What the generator gives you

A folder layout routes, views, public, bin.
A package.json Dependencies and a start script.
A starter app Logging, parsers, static files, 404.
1 / 2

Running the generator

The tool is a command-line program, run once per project. You do not need to install it permanently: npx downloads and runs it.

Terminal
# Read-only: needs npm and a network connection
npx express-generator myapp --view=ejs
cd myapp
npm install
npm start

Then open http://localhost:3000. The most useful options:

Option Meaning
--view=ejs Template engine: ejs, pug, hbs, hjs, jade, twig, vash. Without a choice you get Pug/Jade.
--no-view Do not set up templates at all (good for pure JSON APIs).
--css=sass (or less, stylus, compass) Pre-processor choice for the stylesheet.
--git Also adds a .gitignore.
-f, --force Generate into a folder that is not empty.

For an API you would typically run npx express-generator --no-view --git api and then delete what you do not need.

What it creates

Run with --view=ejs, the generator writes a tree like this:

TEXT
myapp/
โ”œโ”€โ”€ app.js              the application: middleware and routers
โ”œโ”€โ”€ bin/
โ”‚   โ””โ”€โ”€ www             the entry point that starts the HTTP server
โ”œโ”€โ”€ package.json        dependencies and the "start" script
โ”œโ”€โ”€ public/             static files served as-is
โ”‚   โ”œโ”€โ”€ images/
โ”‚   โ”œโ”€โ”€ javascripts/
โ”‚   โ””โ”€โ”€ stylesheets/style.css
โ”œโ”€โ”€ routes/
โ”‚   โ”œโ”€โ”€ index.js        GET /
โ”‚   โ””โ”€โ”€ users.js        GET /users
โ””โ”€โ”€ views/
    โ”œโ”€โ”€ error.ejs       the error page
    โ””โ”€โ”€ index.ejs       the home page

Note how the generator separates two concerns that this course also separates: app.js builds the application and exports it, while bin/www starts the server that listens on a port. That split is the foundation of good testing, as explained in Testing Express Apps, because a test can import the app without opening a port.

The start script in package.json runs node ./bin/www, so npm start launches the server.

Reading the generated app.js

The generated app.js follows a fixed order. Written in modern style, the structure is:

JavaScript
// The shape of the generated app (modernised, not the literal generator output)
import createError from 'http-errors';
import express from 'express';
import logger from 'morgan';
import cookieParser from 'cookie-parser';
import path from 'node:path';

import indexRouter from './routes/index.js';
import usersRouter from './routes/users.js';

const app = express();

app.set('views', path.join(import.meta.dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));                    // request logging  (morgan)
app.use(express.json());                   // parse JSON bodies
app.use(express.urlencoded({ extended: false }));  // parse HTML form bodies
app.use(cookieParser());                   // parse cookies
app.use(express.static(path.join(import.meta.dirname, 'public')));

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

app.use((req, res, next) => next(createError(404)));   // anything unmatched becomes a 404 error

app.use((err, req, res, next) => {         // the error handler (four parameters)
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  res.render('error');
});

export default app;

Every concept here appears in this course: middleware order, built-in parsers, static files, routers, 404 handling and error middleware, and template engines. The generator simply arranges them in the order that works.

Two details worth noticing. The error handler only exposes the error object when the env setting is development (see Application settings), so stack traces do not leak in production. And createError(404) from the http-errors package builds an error with the right status, which the error handler reads.

The entry point, bin/www

The generated bin/www is a script that starts the server. Its job is more than app.listen:

  1. Read the port from process.env.PORT, normalize it (it may be a number, a string pipe name, or invalid) and store it with app.set('port', port).
  2. Create the HTTP server with http.createServer(app).
  3. Listen, and register two handlers: error, which turns the common startup errors (EACCES, EADDRINUSE) into friendly messages, and listening, which logs where it is listening.

You can reproduce that logic in a few lines. The program below starts a server twice on the same port, so the second start fails with EADDRINUSE and the friendly handler explains it:

Node.js The port and error handling a generated bin/www does

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

This is why bin/www exists: the first start prints where it listens, the second explains the problem in plain words instead of a stack trace. Doing this in your own server file is a good habit, and you can see the same ideas in Your First Express App.

What a scaffold really is

Scaffolding is simply a script that writes starter files. To demystify it, here is a miniature generator. It takes a project name and options, builds the files in memory and prints the tree and the generated package.json.

Node.js A toy scaffolding script

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A real generator does the same with templates and a few questions. This toy produces a modern layout, with src/, ES modules and the app/server split, which brings us to the next point.

Modernizing what the generator writes

express-generator is maintained conservatively. When you read this, check what it writes into package.json: at the time of writing it still produces CommonJS (require) code and pins an Express 4 dependency, written in the style of years ago (var, function callbacks). Both still work, but you probably want something newer. After generating, a short cleanup pass is common:

  • Upgrade Express: npm install express@5. Express 5 forwards rejected promises from async handlers to your error middleware and drops several deprecated APIs (Express 5 migration checklist).
  • Switch to ES modules: add "type": "module" to package.json, replace require with import, and module.exports with export default. Use import.meta.dirname instead of __dirname.
  • Rename bin/www to src/server.js and keep the app/server split.
  • Drop what you do not use: cookie-parser if you never read cookies, morgan if you log differently (Logging and Debugging), the sample users router.
  • Add what is missing: a .env loading step (Project Setup), security headers (Security Best Practices), validation, tests.
  • Remove var and the callback style. Running a linter (Code quality tooling) will point to most of them.

Generator or manual setup?

Generator Manual setup
Speed to a running page A minute Ten minutes
You understand every line Maybe not at first Yes, you wrote it
Code style Dated, fixed Your own, current
Good for Demos, workshops, exploring Real projects you will maintain
Typical follow-up Delete and upgrade things Add things as needed

For learning, building the project by hand once, as in Project Setup, teaches you far more. For a throwaway demo, the generator is fine. For production work, many teams either start from their own internal template repository or use a framework built on Express (for example NestJS, see Express vs Fastify, Koa, NestJS and Hapi) that provides its own scaffolding command.

Always run npm audit and read the dependency list of any generated project before building on it. Old scaffolds may pin versions of packages that have since received security fixes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the generated project split app.js from bin/www?

    app.js builds and exports the application; bin/www creates the HTTP server and listens.
  2. 2. Which command creates a project without any template engine?

    --no-view skips views entirely, which suits JSON APIs.
  3. 3. What should you check after generating a project?

    The generator is conservative, so review the generated package.json and modernize what you keep.
  4. 4. In bin/www, what does the error handler on the server mostly handle?

    Listen errors are emitted on the server object, and the handler explains the common ones.

Summary

  • npx express-generator myapp --view=ejs writes a starter project: app.js, bin/www, routes/, views/, public/ and a package.json.
  • app.js arranges logging, parsers, static files, routers, a 404 forwarder and an error handler; bin/www reads the port, creates the server and reports listen errors.
  • The generator writes older-style code (CommonJS, Express 4 pins); upgrade to Express 5 and ES modules if you keep it.
  • Scaffolding is just a script that writes files; a manual setup teaches more and gives you modern code.
  • Always review and audit generated dependencies.

Next: build the same foundation by hand in Project Setup, or compare frameworks in Express vs Fastify, Koa, NestJS and Hapi.