
You can also read the article in English (US).

In this first Express article we answer the questions "What is Node?" and "What is Express?", and give you an overview of what makes the Express web framework special. We'll outline the main features, and show you some of the main building blocks of an Express application (although at this point you won't yet have a development environment in which to test it).

Objective: To gain familiarity with what Express is and how it fits in with Node, what functionality it provides, and the main building blocks of an Express application.

Introducing Node

Node (or more formally Node.js) is an open-source, cross-platform, runtime environment that allows developers to create all kinds of server-side tools and applications in JavaScript. The runtime is intended for use outside of a browser context (i.e. running directly on a computer or server OS). As such, the environment omits browser-specific JavaScript APIs and adds support for more traditional OS APIs including HTTP and file system libraries.

From a web server development perspective Node has a number of benefits:

  • Great performance! Node was designed to optimize throughput and scalability in web applications and is a good solution for many common web-development problems (e.g. real-time web applications).
  • Code is written in "plain old JavaScript", which means that less time is spent dealing with "context shift" between languages when you're writing both client-side and server-side code.
  • JavaScript is a relatively new programming language and benefits from improvements in language design when compared to other traditional web-server languages (e.g. Python, PHP, etc.) Many other new and popular languages compile/convert into JavaScript so you can also use TypeScript, CoffeeScript, ClojureScript, Scala, LiveScript, etc.
  • The node package manager (NPM) provides access to hundreds of thousands of reusable packages. It also has best-in-class dependency resolution and can also be used to automate most of the build toolchain.
  • Node.js is portable. It is available on Microsoft Windows, macOS, Linux, Solaris, FreeBSD, OpenBSD, WebOS, and NonStop OS. Furthermore, it is well-supported by many web hosting providers, that often provide specific infrastructure and documentation for hosting Node sites.
  • It has a very active third party ecosystem and developer community, with lots of people who are willing to help.

You can use Node.js to create a simple web server using the Node HTTP package.

Hello Node.js

The following example creates a web server that listens for any kind of HTTP request on the URL — when a request is received, the script will respond with the string: "Hello World". If you have already installed node, you can follow these steps to try out the example:

  1. Open Terminal (on Windows, open the command line utility)
  2. Create the folder where you want to save the program, for example, "test-node" and then enter it by entering the following command into your terminal:
cd test-node
  1. Using your favorite text editor, create a file called "hello.js" and paste the following code into it:
// Load HTTP module
const http = require("http");

const hostname = "";
const port = 8000;

// Create HTTP server 

   // Send the response body "Hello World"
   res.end('Hello World\n');

// Prints a log once the server starts listening
server.listen(port, hostname, () => {
  1. Save the file in the folder you created above.
  2. Go back to the terminal and type the following command:
node "hello.js"

Finally, navigate to "http://localhost:8000" in your web browser; you should see the text "Hello World" in the upper left of an otherwise empty web page.

Web Frameworks

Other common web-development tasks are not directly supported by Node itself. If you want to add specific handling for different HTTP verbs (e.g. GET, POST, DELETE, etc.), separately handle requests at different URL paths ("routes"), serve static files, or use templates to dynamically create the response, then you will need to write the code yourself, or you can avoid reinventing the wheel and use a web framework!

Introducing Express

Express is the most popular Node web framework, and is the underlying library for a number of other popular Node web frameworks. It provides mechanisms to:

  • Write handlers for requests with different HTTP verbs at different URL paths (routes).
  • Integrate with "view" rendering engines in order to generate responses by inserting data into templates.
  • Set common web application settings like the port to use for connecting, and the location of templates that are used for rendering the response.
  • Add additional request processing "middleware" at any point within the request handling pipeline.

While Express itself is fairly minimalist, developers have created compatible middleware packages to address almost any web development problem. There are libraries to work with cookies, sessions, user logins, URL parameters, POST data, security headers, and many more. You can find a list of middleware packages maintained by the Express team at Express Middleware (along with a list of some popular 3rd party packages).


Where did Node and Express come from?

Node was initially released, for Linux only, in 2009. The NPM package manager was released in 2010, and native Windows support was added in 2012. The current LTS release is Node v10.16.0 while the latest release is Node 12.4.0. This is a tiny snapshot of a rich history; delve into Wikipedia if you want to know more.

Express was initially released in November 2010 and is currently on version 4.17.1 of the API. You can check out the changelog for information about changes in the current release, and GitHub for more detailed historical release notes.




Is Express opinionated?





What does Express code look like?




Helloworld Express


Tip: If you have Node and Express already installed (or if you install them as shown in the next article), you can save this code in a text file called app.js and run it in a bash command prompt by calling:   

node ./app.js

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

  res.send('Hello World!');

app.listen(3000, function() {




Importing and creating modules



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



To make objects available outside of a module you just need to expose them as additional properties on the exports object. For example, the square.js module below is a file that exports area() and perimeter() methods:






module.exports = {
  area: function(width) {
    return width * width;
  perimeter: function(width) {
    return 4 * width;

Note: You can think of exports as a shortcut to module.exports within a given module. In fact, exports is just a variable that gets initialized to the value of module.exports before the module is evaluated. That value is a reference to an object (empty object in this case). This means that exports holds a reference to the same object referenced by module.exports. It also means that by assigning another value to exports it's no longer bound to module.exports.


Using asynchronous APIs




setTimeout(function() {
   }, 3000);

Using non-blocking asynchronous APIs is even more important on Node than in the browser because Node is a single-threaded event-driven execution environment. "Single threaded" means that all requests to the server are run on the same thread (rather than being spawned off into separate processes). This model is extremely efficient in terms of speed and server resources, but it does mean that if any of your functions call synchronous methods that take a long time to complete, they will block not just the current request, but every other request being handled by your web application.


Tip: Using callbacks can be quite "messy" if you have a sequence of dependent asynchronous operations that must be performed in order because this results in multiple levels of nested callbacks. This problem is commonly known as "callback hell". This problem can be reduced by good coding practices (see http://callbackhell.com/), using a module like async, or even moving to ES6 features like Promises.

Note: A common convention for Node and Express is to use error-first callbacks. In this convention, the first value in your callback functions is an error value, while subsequent arguments contain success data. There is a good explanation of why this approach is useful in this blog: The Node.js Way - Understanding Error-First Callbacks (fredkschott.com).

Creating route handlers

In our Hello World Express example (see above), we defined a (callback) route handler function for HTTP GET requests to the site root ('/').

  res.send('Hello World!');

The callback function takes a request and a response object as arguments. In this case, the method simply calls send() on the response to return the string "Hello World!" There are a number of other response methods for ending the request/response cycle, for example, you could call res.json() to send a JSON response or res.sendFile() to send a file.



checkout()copy()delete()get()head()lock()merge()mkactivity(), mkcol(), move(), m-search(), notify(), options(), patch(), post(), purge(), put(), report(), search(), subscribe(), trace(), unlock(), unsubscribe().


  console.log('Accessing the secret section ...');
  next(); // pass control to the next handler



// wiki.js - Wiki route module

var express = require('express');
var router = express.Router();

// Home page route
  res.send('Wiki home page');

// About page route
  res.send('About this wiki');

module.exports = router;



var wiki = require('./wiki.js');
// ...
app.use('/wiki', wiki);


Using middleware


Note: The middleware can perform any operation, execute any code, make changes to the request and response object, and it can also end the request-response cycle. If it does not end the cycle then it must call next() to pass control to the next middleware function (or the request will be left hanging).



$ npm install morgan


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


You can write your own middleware functions, and you are likely to have to do so (if only to create error handling code). The only difference between a middleware function and a route handler callback is that middleware functions have a third argument next, which middleware functions are expected to call if they are not that which completes the request cycle (when the middleware function is called, this contains the next function that must be called).



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

// An example middleware function
var a_middleware_function = function(req, res, next) {
  // ... perform some operations


// Function added with use() for a specific route
app.use('/someroute', a_middleware_function);

app.get('/', a_middleware_function);




Serving static files








app.use('/media', express.static('public'));



For more information, see Serving static files in Express.

Handling errors


  res.status(500).send('Something broke!');



Note: The stack trace is not included in the production environment. To run it in production mode you need to set the environment variable NODE_ENV to 'production'.


For more information see Error handling (Express docs).

Using databases



$ npm install mongodb


//this works with older versions of  mongodb version ~ 2.2.33
var MongoClient = require('mongodb').MongoClient;

  if (err) throw err;

    if (err) throw err;


//for mongodb version 3.0 and up
let MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/animals', function(err, client){
   if(err) throw err;
   let db = client.db('animals');
     if(err) throw err;





For more information see Database integration (Express docs).

Rendering data (views)



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


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




File structure






See also

In this module