ExpressJS Cheatsheet



In this cheatsheet, we will cover the essential features and concepts of Express.js, including routing, middleware, request handling, and working with templates. Well also dive into how to set up a basic server, handle different HTTP methods, and manage static files. Whether you're building APIs or web applications, this guide will provide quick references to help you work more efficiently with Express.js.

Table of Contents

Introduction

Express.js is a fast, minimalist web framework for Node.js, designed to simplify building web applications and APIs. It provides robust features for handling routes, middleware, and HTTP requests and responses.

Express.js Basics

Create a Project

$ mkdir myapp       
$ cd myapp          # Enter the directory 
$ npm init -y      

Install Dependencies

The command installs the express framework, a minimal and flexible web application framework for Node.js.

$ npm install express

Create an Entry File (index.js)

The code creates an entry file index.js that sets up a basic Express server. It listens on port 3000 and responds with "Hello World!" when the root URL (/) is accessed.

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
    res.send('Hello World!');
});
app.listen(port, () => {
    console.log(`Listening on port ${port}`);
});

Run the Application

The command node index.js runs the application by executing the index.js file, starting the Express server, which listens on port 3000 and serves responses to incoming requests.

$ node index.js

Common CLI Commands

CLI commands include creating and navigating directories, initializing the project (npm init -y), installing dependencies (npm install express), and running the application (node index.js).

Initialize with Pug Template

The commands initialize an Express app using the Pug template engine (express --view=pug myapp), navigate to the app directory (cd myapp), install dependencies (npm install), and start the server (npm start).

$ express --view=pug myapp
$ cd myapp
$ npm install
$ npm start
Option Explanation
-h, --help Output usage information
--version Output version number
-e, --ejs Add EJS template engine support
--hbs Add HBS template engine support
--pug Add Pug template engine support
-v, --view <engine> Specify a view engine (e.g., ejs, pug)
-c, --css <engine> Specify a CSS engine (default: CSS)
--git Add .gitignore
-f, --force Force creation in non-empty directories

Routing

Routing in Express defines how the application responds to client requests for specific URLs (endpoints) and HTTP methods (e.g., GET, POST).

Basic Routes

Basic routes define handlers for specific HTTP methods: GET serves content (e.g., 'GET request to the homepage'), POST processes submissions, and DELETE removes resources.

app.get('/', (req, res) => res.send('GET request to the homepage'));
app.post('/', (req, res) => res.send('POST request to the homepage'));
app.delete('/user/:id', (req, res) => res.send(`DELETE user ${req.params.id}`));

Route Middleware

Route middleware in Express allows for pre-processing requests before they reach the route handler.

app.all('/secret', (req, res, next) => {
    console.log('Accessing secret section...');
    next();
});

Middleware

Middleware functions are functions that interact with the request object (req), the response object (res), and the next middleware in the application's request-response cycle. They are commonly used to process or modify req and res objects, enabling tasks such as request body parsing, adding response headers, and more.

Global Middleware

Global middleware in Express is applied to all routes and requests. It can be used for logging, authentication, etc.

app.use((req, res, next) => {
    console.log('Time:', Date.now());
    next();
});

Custom Middleware

Custom middleware in Express allows you to define the processing logic for requests.

Template

A template is a file that defines the structure of a view in an application. In Express, a template engine is used to render dynamic content to the user.

Set View Engine

To configure the application to use a specific template engine, such as Pug, you set the view engine using app.set().

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

Pug Template Example (views/index.pug)

A Pug template defines the structure of an HTML page using variables and dynamic content.

html
  head
    title= title
  body
    h1= message

Render Template

The res.render() method in Express is used to render a specified template (e.g., index.pug) and pass dynamic data (like title and message) to it.

app.get('/', (req, res) => {
    res.render('index', { title: 'Hey', message: 'Hello there!' });
});

Request and Response

Request (req): The object representing the HTTP request, containing details like request headers, query parameters, body, and URL.Response (res): The object used to send the HTTP response back to the client, including status codes, headers, and response body.

Request Object (req)

Property Explanation
req.params Route parameters (e.g., /user/:id)
req.query Query string parameters
req.body Body of the request (requires parsing)
req.method HTTP method (GET, POST, etc.)
req.originalUrl Full URL of the request

Example

app.get('/user/:id', (req, res) => {
    res.send(`User ID: ${req.params.id}`);
});

Response Object (res)

Method Explanation
res.send() Send a response
res.json() Send a JSON response
res.render() Render a template
res.redirect() Redirect to another URL
res.status() Set the HTTP status code

Example

app.get('/status', (req, res) => {
    res.status(200).json({ status: 'OK' });
});

Router

A router in Express allows you to define route handlers for specific paths, making your application modular.

Create a Router

creates a router for handling the /events route, responding with the text 'Events' when accessed.

const router = express.Router();

router.get('/events', (req, res) => {
    res.send('Events');
});

app.use('/api', router);

Application Methods

Method Explanation
app.use() Mount middleware functions
app.get() Handle GET requests
app.post() Handle POST requests
app.listen() Bind the application to a port
app.set() Set application variables
app.engine() Define a custom template engine

Error Handling

Error handling middleware in Express catches and processes errors that occur during request processing.

app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

Debugging

Debugging is achieved in Express using the Debug module to log information like route matching, middleware functions, and application mode.

Run with debug mode

Running with debug mode enables detailed logging for your application.

$ DEBUG=myapp:* npm start

Database integration

Database integration involves connecting a web application to a database system (like Cassandra or MySQL) to store, retrieve, and manage data.

Cassandra Integration

To integrate Cassandra with an Express app, install the Cassandra-driver package. After installation, configure the Cassandra client by specifying contact points (e.g., localhost) and the local data center.

Installation

$ npm install express cassandra-driver

Cassandra

const { Client } = require('cassandra-driver');

const cassandraClient = new Client({
  contactPoints: ['localhost'],
  localDataCenter: 'datacenter1',
});

MySQL Integration

To integrate MySQL with an Express app, install the mysql package. This allows you to connect to a MySQL database and execute SQL queries within your application.

Installation

$ npm install express mysql

MySQL

The code establishes a connection to a MySQL database using the mysql package. It connects to a database with the specified credentials (host, user, password)

const mysql = require('mysql');

const db = mysql.createConnection({
  host: 'localhost',
  user: 'dbuser',
  password: 'yourpassword',
  database: 'your_database',
});

db.connect((err) => {
  if (err) {
    console.error('Error connecting to MySQL:', err.message);
  } else {
    console.log('Connected to MySQL!');
  }
});

MongoDB Integration

To integrate MongoDB with Express, the Mongodb package is installed. After installation, you can connect to MongoDB and interact with the database using its client.

Installation

$ npm install express mongodb

MongoDB

The MongoClient is used to connect to MongoDB via a specified URI (mongodb://localhost:27017). The connection is established asynchronously using await within a try-catch block for error handling.

const { MongoClient } = require('mongodb');

const uri = 'mongodb://localhost:27017'; // Connection URL
const client = new MongoClient(uri);

async function connectToDatabase() {
  try {
    await client.connect();
    console.log('Connected to MongoDB');
    return client.db('animals'); // Specify your database
  } catch (err) {
    console.error('Error connecting to MongoDB:', err.message);
    throw err;
  }
}

Authentication

Authentication in an Express app verifies the identity of users, typically through login forms, by comparing credentials with stored data and managing user sessions for access control.

Install Dependencies

$ npm init -y
$ npm install express jsonwebtoken bcryptjs mongoose

Server Setup

Set up the Express server to handle incoming requests, configure middleware for session management, and initialize authentication strategies (e.g., Passport).

const express = require('express');
const app = express();
app.use(express.json());

// Import Routes
const authRoutes = require('./routes/index');
app.use('/api', authRoutes);

const PORT = 3000;
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));

Routes Setup

Define routes for login, logout, registration, and other user actions, using middleware to authenticate users and manage sessions.

const router = require('express').Router();
const userController = require('../controllers/user');
const { verifyUserToken, IsUser, IsAdmin } = require('../middleware/auth');

// Register, Login, and Protected Routes
router.post('/register', userController.register);
router.post('/login', userController.login);
router.get('/events', verifyUserToken, IsUser, userController.userEvent);
router.get('/special', verifyUserToken, IsAdmin, userController.adminEvent);

module.exports = router;

User Registration and Login

User registration and login involve creating routes to allow users to register by providing credentials and login in using those credentials, often with session management to maintain the user state.

const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/User');  // Assuming User model exists

// Register User
exports.register = async (req, res) => {
  const hashedPassword = await bcrypt.hash(req.body.password, 10);
  const newUser = new User({
    email: req.body.email,
    name: req.body.name,
    password: hashedPassword,
  });
  newUser.save()
    .then(user => {
      const token = jwt.sign({ id: user._id }, 'yourSecretKey');
      res.status(200).send({ token });
    })
    .catch(err => res.status(500).send(err));
};

// Login User
exports.login = async (req, res) => {
  const user = await User.findOne({ email: req.body.email });
  if (!user) return res.status(400).send('User not found');
  
  const isMatch = await bcrypt.compare(req.body.password, user.password);
  if (!isMatch) return res.status(400).send('Invalid password');
  
  const token = jwt.sign({ id: user._id }, 'yourSecretKey');
  res.status(200).send({ token });
};

Authentication Middleware

Authentication middleware checks if the user is authenticated before granting access to certain routes, typically using session data or tokens to verify the user's identity.

const jwt = require('jsonwebtoken');

// Verify Token
exports.verifyUserToken = (req, res, next) => {
  const token = req.headers.authorization && req.headers.authorization.split(' ')[1];
  if (!token) return res.status(401).send('Access Denied');
  
  jwt.verify(token, 'yourSecretKey', (err, user) => {
    if (err) return res.status(400).send('Invalid Token');
    req.user = user;
    next();
  });
};

// Role-Based Authorization
exports.IsUser = (req, res, next) => {
  if (req.user.user_type_id === 0) return next();
  res.status(401).send('Unauthorized');
};

exports.IsAdmin = (req, res, next) => {
  if (req.user.user_type_id === 1) return next();
  res.status(401).send('Unauthorized');
};

Security

Security in web applications involves implementing measures like encryption, session management, and middleware to protect data and prevent vulnerabilities such as unauthorized access and attacks.

Install Helmet.js

Helmet.js is a security middleware that helps secure Express apps by setting HTTP headers to protect against common security vulnerabilities.

$ npm install helmet

Server Setup with Helmet.js

Helmet.js is integrated into the Express app to set secure HTTP headers and protect the app from common web vulnerabilities by adding middleware.

const express = require('express');
const helmet = require('helmet');
const app = express();

// Security Middleware
app.use(helmet());  // Automatically adds multiple security-related HTTP headers

app.get('/', (req, res) => {
  res.send('Hello, secure world!');
});

const port = 3000;
app.listen(port, () => {
  console.log(`Server running securely on http://localhost:${port}`);
});

Install tiny-csrf

tiny-csrf is a library used to generate and verify CSRF (Cross-Site Request Forgery) using its tokens to prevent malicious requests.

npm install tiny-csrf

CSRF Middleware

CSRF middleware generates a token and ensures that incoming requests contain a valid token to prevent CSRF attacks.

const TinyCSRF = require("tiny-csrf");
const csrfMiddleware = TinyCSRF(process.env.CSRF_SECRET, ["POST", "PUT", "DELETE", "PATCH"], {
  getTokenFromRequest: (req) => req.cookies['csrf'],
  secure: true,
  maxAge: 3600
});

Generate and Send CSRF Token

CSRF tokens are generated and sent to the client, typically via cookies or embedded in forms, to be included in future requests to verify their authenticity.

const csrfTokenRoute = (req, res) => {
  const csrfToken = req.csrfToken();
  res.cookie('csrf', csrfToken, {
    httpOnly: false,
    secure: true,
    sameSite: 'Strict'
  });
  res.json({ csrfToken });
};

Apply CSRF Middleware and Route

CSRF middleware is applied to routes that modify data, ensuring each request has a valid CSRF token to prevent malicious form submissions.

app.use(csrfMiddleware); // Apply middleware globally

app.get('/csrf-token', csrfTokenRoute); // Route to get CSRF token

Testing

Unit Tests

Unit tests ensure individual components or functions of your application work as expected by testing them in isolation.

Install Mocha, Chai, and Supertest

Mocha is a test framework, Chai provides assertion functions, and Supertest allows for HTTP assertions in integration tests for your Express app.

npm install mocha chai supertest

GreetingService.js

GreetingService provides a method to generate greeting messages, and the Express router uses this service to handle HTTP requests, sending a greeting message back to the client.

class GreetingService {
  greet(name) {
    return `Hello, ${name}!`;
  }
}
module.exports = GreetingService;
routes.js

const express = require('express');
const GreetingService = require('./GreetingService');

const router = express.Router();
const greetingService = new GreetingService();

router.get('/greet/:name', (req, res) => {
  const { name } = req.params;
  const greetingMessage = greetingService.greet(name);
  res.send({ message: greetingMessage });
});

module.exports = router;

routes.test.js

The code tests an Express app using Mocha, Chai, and Supertest, checking that a GET request to the /greet/:name route responds with a 200 status and a message containing the correct greeting.

const { expect } = require('chai');
const request = require('supertest');
const express = require('express');
const routes = require('../routes');

describe('Express App', () => {
  const app = express();
  app.use('/', routes);

  it('should respond with a greeting message', async () => {
    const response = await request(app).get('/greet/John');
    expect(response.status).to.equal(200);
    expect(response.body).to.have.property('message');
    expect(response.body.message).to.equal('Hello, John!');
  });
});

Integration Tests in Express.js

Install Chai-Http
npm install chai-http

Integration Test

const chai = require('chai');
const chaiHttp = require('chai-http');
const app = require('../app');
chai.use(chaiHttp);
const expect = chai.expect;
describe('Integration Tests for User Management', () => {
  it('should create a new user', (done) => {
    chai.request(app)
      .post('/api/users')
      .send({ username: 'braveknight', password: 'secret' })
      .end((err, res) => {
        expect(res).to.have.status(201);
        expect(res.body).to.have.property('userId');
        done();
      });
  });
it('should retrieve user information', (done) => {
    chai.request(app)
      .get('/api/users/braveknight')
      .end((err, res) => {
        expect(res).to.have.status(200);
        expect(res.body.username).to.equal('braveknight');
        done();
      });
  });
});

Deployment (Vercel)

Vercel is a cloud platform for static sites and serverless functions. It simplifies the deployment process for web applications.

Create a New Project

Create a new project directory and initialize it for deployment using Vercel.

mkdir new-express-project
cd new-express-project npm init -y

Install Express.js

Install Express.js in the project to set up the server framework.

npm install express

Set Up Express.js App

Set up an Express app by creating a basic app.js file to handle incoming HTTP requests.

const express = require("express");
const app = express();

app.get("/", (req, res) => res.send("Express on Vercel"));

module.exports = app;

Create vercel.json

Create a vercel.json configuration file to define deployment settings such as build options and routes.

{
  "version": 2,
  "rewrites": [
    { "source": "/(.*)", "destination": "/api" }
  ]
}

Run Locally Using Vercel CLI

Use the Vercel CLI to run your app locally before deploying it.

Install Vercel CLI

Install the Vercel CLI globally to interact with the Vercel platform -g vercel.

npm install -g vercel

Login to Vercel

Log in to Vercel through the CLI to link your project with your Vercel account vercel login.

vercel login

Run your app locally

Use the Vercel CLI to run your application locally for testing before deployment.

vercel dev

Deploy to Vercel

Deploy your app to Vercel by running the deploy command Vercel.

vercel

Promote to Production

Promote your app to production after successful deployment, making it live for the public.

vercel --prod
Advertisements