Getting Started with Express: Build Your First Node.js Web App

This guide introduces Express, a Node.js web framework, covering its advantages, environment setup, a step‑by‑step demo project, directory layout, core concepts such as routing, middleware and template engines, and practical code examples to help beginners launch a functional server quickly.

Tencent IMWeb Frontend Team
Tencent IMWeb Frontend Team
Tencent IMWeb Frontend Team
Getting Started with Express: Build Your First Node.js Web App

Introduction

Express is a web development framework based on Node.js. Its advantages are ease of use, high performance, and strong extensibility.

Easy to learn : Express wraps many low‑level Node.js APIs, shielding developers from complex details so they can focus on business logic.

High performance : It adds only modest abstraction, avoiding the overhead of heavy wrappers.

Strong extensibility : The middleware‑based architecture makes extending and modularizing an app simple and flexible.

Environment Setup

First install Node.js (instructions omitted). Then install the Express generator tool:

npm install -g express-generator

First Demo

Use the generator to create a demo project:

/tmp mkdir express-demo
/tmp cd express-demo
express-demo express

# generated files and directories
create : .
create : ./package.json
create : ./app.js
create : ./public
create : ./public/javascripts
create : ./public/images
create : ./public/stylesheets
create : ./public/stylesheets/style.css
create : ./routes
create : ./routes/index.js
create : ./routes/users.js
create : ./views
create : ./views/index.jade
create : ./views/layout.jade
create : ./views/error.jade
create : ./bin
create : ./bin/www

# install dependencies
cd . && npm install
# start the app
DEBUG=express-demo:* npm start

Install dependencies and start the server:

npm install
express-demo npm start

> [email protected] start /private/tmp/ex1
> node ./bin/www

Open a browser to see the running application.

Directory Structure Overview

The typical Express project layout looks like this:

.
├── app.js            # main entry point
├── bin               # startup scripts
├── node_modules      # dependencies
├── package.json      # module configuration
├── public            # static assets (css, js, images)
├── routes            # route definitions
└── views             # template files

Core Concepts Overview

Express revolves around three core concepts: routing, middleware, and template engine.

Note: The term “core concepts” is used here instead of “core modules” because Express’s source code does not contain a distinct middleware module; middleware is a design pattern rather than a separate module.
Middleware

: In an Express app, everything can be treated as middleware—e.g., cookie parsing, session handling, logging, authentication. Routing: Determines which resource handles an incoming HTTP request. Template Engine: Renders dynamic views; configuration and custom engine development are covered later.

Routing

Routing Types

Express supports four routing styles:

String routes

String pattern routes

Regular‑expression routes

Parameter routes

Examples:

var express = require('express');
var app = express();

// String route
app.get('/book', function(req, res, next){
    res.send('book');
});

// String pattern route
app.get('/user/*man', function(req, res, next){
    res.send('user'); // matches /user/man, /user/woman
});

// RegExp route
app.get(/animals?$/, function(req, res, next){
    res.send('animal'); // matches /animal, /animals
});

// Parameter route
app.get('/employee/:uid/:age', function(req, res, next){
    res.json(req.params); // e.g., /111/30 returns {"uid":111,"age":30}
});

app.listen(3000);

Route Splitting

As an application grows, splitting routes improves maintainability. Before splitting:

var express = require('express');
var app = express();

app.get('/user/list', function(req, res, next){
    res.send('/list');
});

app.get('/user/detail', function(req, res, next){
    res.send('/detail');
});

app.listen(3000);

After splitting with express.Router():

var express = require('express');
var app = express();
var user = express.Router();

user.get('/list', function(req, res, next){
    res.send('/list');
});

user.get('/detail', function(req, res, next){
    res.send('/detail');
});

app.use('/user', user); // mount the router
app.listen(3000);

Middleware

In Express, everything is middleware, from request parsing to compression.

How Middleware Works

A minimal middleware function looks like this:

function logger(req, res, next){
    console.log('here comes request');
    next();
}

Example chain:

var express = require('express');
var app = express();

app.use(function(req, res, next){ console.log('1'); next(); });
app.use(function(req, res, next){ console.log('2'); next(); });
app.use(function(req, res, next){ console.log('3'); res.send('hello'); });

app.listen(3000);

Running http://127.0.0.1:3000 prints 1, 2, 3 in the console and returns “hello”.

Application‑Level vs. Router‑Level Middleware

Application‑level: used via app.use() or app.METHOD().

Router‑level: used via router.use() or router.METHOD().

var express = require('express');
var app = express();
var user = express.Router();

// Application‑level middleware
app.use(function(req, res, next){
    console.log('Request URL:', req.url);
    next();
});

app.get('/profile', function(req, res){ res.send('profile'); });

// Router‑level middleware
user.use('/list', function(req, res){ res.send('/user/list'); });
user.get('/detail', function(req, res){ res.send('/user/detail'); });

app.use('/user', user);
app.listen(3000);

Creating Custom Middleware

function logger(req, res, next){
    // business logic such as auth, DB ops, setting cookies
    next();
}

Common Middleware Packages

body-parser

compression

serve-static

session

cookie-parser

morgan

Template Engine

Express supports many template engines (e.g., jade, ejs, dust.js, dot, mustache, handlebars, nunjucks). Configuration typically involves setting the views directory and the view engine:

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

To use Nunjucks:

npm install --save nunjucks

var nunjucks = require('nunjucks');

nunjucks.configure('views', {
    autoescape: true,
    express: app
});

app.set('view engine', 'html');

Example views/layout.html:

<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}layout title{% endblock %}</title>
</head>
<body>
    <h1>{% block appTitle %}layout app title{% endblock %}</h1>
    <p>正文</p>
</body>
</html>

Example views/index.html extending the layout:

{% extends "layout.html" %}
{% block title %}首页{% endblock %}
{% block appTitle %}首页{% endblock %}

Registering a Custom Engine

app.engine('tmpl', function(filepath, options, callback){
    // render logic
    return callback(null, 'Hello World');
});
app.set('views', './views');
app.set('view engine', 'tmpl');

Further Topics

The article mentions additional advanced topics such as process management, session handling, logging, performance optimization, debugging, error handling, load balancing, database integration, HTTPS support, and real‑world use cases, which can be explored in future posts.

Related Links

Express official website: http://expressjs.com/

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendmiddlewareroutingnodejsExpressTemplate Engineweb-development
Tencent IMWeb Frontend Team
Written by

Tencent IMWeb Frontend Team

IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.