Express.js

From David's Wiki
\( \newcommand{\P}[]{\unicode{xB6}} \newcommand{\AA}[]{\unicode{x212B}} \newcommand{\empty}[]{\emptyset} \newcommand{\O}[]{\emptyset} \newcommand{\Alpha}[]{Α} \newcommand{\Beta}[]{Β} \newcommand{\Epsilon}[]{Ε} \newcommand{\Iota}[]{Ι} \newcommand{\Kappa}[]{Κ} \newcommand{\Rho}[]{Ρ} \newcommand{\Tau}[]{Τ} \newcommand{\Zeta}[]{Ζ} \newcommand{\Mu}[]{\unicode{x039C}} \newcommand{\Chi}[]{Χ} \newcommand{\Eta}[]{\unicode{x0397}} \newcommand{\Nu}[]{\unicode{x039D}} \newcommand{\Omicron}[]{\unicode{x039F}} \DeclareMathOperator{\sgn}{sgn} \def\oiint{\mathop{\vcenter{\mathchoice{\huge\unicode{x222F}\,}{\unicode{x222F}}{\unicode{x222F}}{\unicode{x222F}}}\,}\nolimits} \def\oiiint{\mathop{\vcenter{\mathchoice{\huge\unicode{x2230}\,}{\unicode{x2230}}{\unicode{x2230}}{\unicode{x2230}}}\,}\nolimits} \)

Express.js, also known as Express, is a Node.js web-framework.
It provides access to routing and a rich community of middleware.

The benefit to using JS/TS for your backend is that your full stack is in a single-language.
This also means you can use all of your favorite libraries on npm.

However, since JS is single-threaded, you need to be careful with optimization (i.e. async programming).
Deployment may require running multiple instances of your application even on the same VM.

Getting Started

To create a project, do

npx express-generator --view=pug

or

npm i -g express-generator
express --view=pug [dir]

See express starter generator for more details.

  • By default, express uses jade for its template engine. This has been replaced by pug.
  • If you want to make a typescript project, you can also try express-generator-typescript.
    • This is made by a third-party and includes some extra libraries.

Usage

Routing

See Guide: Routing

Database

See Express database integration

Express does not provide any special methods for interacting with databases.

Below are some ways of interacting with databases.

  • Sequelize is an object-relation mapping (ORM) for Node. It supports Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server.
  • TypeORM is another ORM from Node.
  • Knex.js is an SQL query builder.
  • Objection.js is another ORM built on Knex.js.

Proxies

It is typically recommended to run express behind a proxy (e.g. Nginx) for production.
See guide: behind-proxies for how to configure this such that the client hostname is correct.

app.set('trust proxy', 'loopback');

Libraries

Some common libraries and middleware

Resources