Setting Up Express.js App

Setting up an Express.js application involves several steps, from installing the necessary tools to creating a basic server, adding routes, and implementing advanced features. This chapter will guide you through the entire process, ensuring you have a solid foundation for building Express.js applications.

Prerequisites

Before you start setting up an Express.js application, make sure you have the following:

  • Basic understanding of JavaScript
  • A code editor (e.g., Visual Studio Code)
  • Node.js installed on your computer

Installing Node.js and NPM

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. NPM (Node Package Manager) is included with Node.js and is used to install packages.

Step-by-Step Installation:

  1. Go to the Node.js official website.
  2. Download the LTS (Long Term Support) version suitable for your operating system.
  3. Run the installer and follow the instructions.

To verify the installation, open your terminal or command prompt and run:

				
					node -v
npm -v

				
			

This should display the installed versions of Node.js and NPM.

Initializing a New Node.js Project

To start a new Node.js project, you need to create a project directory and initialize it.

Step-by-Step Initialization:

Create a new directory for your project.

				
					mkdir my-express-app
cd my-express-app

				
			

Initialize a new Node.js project.

				
					npm init -y

				
			

This will create a package.json file with default settings.

Installing Express.js

Express.js can be installed using NPM. This package will provide the core functionality for your application.

				
					npm install express

				
			

This will add Express.js to your project and update the package.json file with the dependency.

Creating a Basic Express.js Server

With Express.js installed, you can create a basic server to handle HTTP requests and responses.

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

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

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

				
			

Explanation:

  • require('express'): Imports the Express.js module.
  • const app = express(): Creates an Express application.
  • app.get('/', (req, res) => {...}): Defines a route for the root URL that sends a “Hello, World!” response.
  • app.listen(PORT, () => {...}): Starts the server on the specified port.

Output: When you navigate to http://localhost:3000 in your browser, you will see “Hello, World!”.

Setting Up Routes

Routes are used to define the endpoints of your application. Each route can handle different types of HTTP requests.

				
					app.get('/about', (req, res) => {
  res.send('About Page');
});

app.post('/submit', (req, res) => {
  res.send('Form Submitted');
});

				
			

Explanation:

  • app.get('/about', (req, res) => {...}): Defines a GET route for the /about URL.
  • app.post('/submit', (req, res) => {...}): Defines a POST route for the /submit URL.

Output:

  • Navigating to http://localhost:3000/about displays “About Page”.
  • Sending a POST request to http://localhost:3000/submit displays “Form Submitted”.

Middleware

Middleware functions are used to handle various tasks such as logging, parsing request bodies, and authentication.

				
					app.use((req, res, next) => {
  console.log(`${req.method} request for ${req.url}`);
  next();
});

app.use(express.json());

				
			

Explanation:

  • app.use((req, res, next) => {...}): Logs each request’s method and URL.
  • app.use(express.json()): Parses incoming JSON request bodies.

Output: Each request will be logged in the console, and JSON request bodies will be automatically parsed.

Serving Static Files

Express can serve static files such as HTML, CSS, and JavaScript.

				
					app.use(express.static('public'));

				
			

Explanation:

  • app.use(express.static('public')): Serves static files from the public directory.

Output: Files in the public directory will be accessible via URLs like http://localhost:3000/file.html.

Template Engines

Template engines allow you to generate HTML dynamically. Express supports various template engines such as Pug, EJS, and Handlebars.

Example with Pug:

				
					npm install pug

				
			

Set up Pug in your Express application.

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

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

				
			

Create a Pug template file (views/index.pug).

				
					html
  head
    title= title
  body
    h1= message

				
			

Output: Navigating to http://localhost:3000/template will render the Pug template with the title “Express” and the message “Hello, Pug!”.

Error Handling

Error handling middleware functions handle errors that occur in the application.

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

				
			

Explanation:

  • app.use((err, req, res, next) => {...}): Handles errors and sends a 500 status code with an error message.

Output: If an error occurs, the console will log the error stack, and the response will be “Something went wrong!”.

Using Environment Variables

Environment variables are used to configure the application without hardcoding values.

Install dotenv.

				
					npm install dotenv

				
			

Create a .env file.

				
					PORT=3000

				
			

Load environment variables in your application.

				
					require('dotenv').config();
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

				
			

Output: The server will start on the port specified in the .env file or default to 3000.

Connecting to a Database

Express.js can be integrated with various databases. Here, we will use MongoDB with Mongoose.

Install Mongoose.

				
					npm install mongoose

				
			

Connect to MongoDB.

				
					const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true, useUnifiedTopology: true });

const userSchema = new mongoose.Schema({
  name: String,
  email: String
});

const User = mongoose.model('User', userSchema);

app.post('/users', async (req, res) => {
  const user = new User({
    name: req.body.name,
    email: req.body.email
  });
  await user.save();
  res.status(201).send(user);
});

app.get('/users', async (req, res) => {
  const users = await User.find();
  res.json(users);
});

				
			

Explanation:

  • mongoose.connect(...): Connects to the MongoDB database.
  • const userSchema = new mongoose.Schema(...): Defines a schema for the User model.
  • const User = mongoose.model('User', userSchema): Creates a User model.
  • app.post('/users', async (req, res) => {...}): Adds a new user to the database.
  • app.get('/users', async (req, res) => {...}): Retrieves all users from the database.

Output: Using tools like Postman, you can add and retrieve users from the MongoDB database.

Combined Code Example

Project Structure:

				
					my-express-app/
├── public/
│   └── index.html
├── views/
│   └── index.pug
├── .env
├── app.js
├── package.json
└── package-lock.json

				
			

.env File:

				
					PORT=3000
MONGO_URI=mongodb://localhost:27017/test

				
			

public/index.html:

				
					<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Express App</title>
</head>
<body>
    <h1>Welcome to the Express App</h1>
    <p>This is a static file served by Express.</p> <script data-no-optimize="1">!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).LazyLoad=e()}(this,function(){"use strict";function e(){return(e=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n,a=arguments[e];for(n in a)Object.prototype.hasOwnProperty.call(a,n)&&(t[n]=a[n])}return t}).apply(this,arguments)}function i(t){return e({},it,t)}function o(t,e){var n,a="LazyLoad::Initialized",i=new t(e);try{n=new CustomEvent(a,{detail:{instance:i}})}catch(t){(n=document.createEvent("CustomEvent")).initCustomEvent(a,!1,!1,{instance:i})}window.dispatchEvent(n)}function l(t,e){return t.getAttribute(gt+e)}function c(t){return l(t,bt)}function s(t,e){return function(t,e,n){e=gt+e;null!==n?t.setAttribute(e,n):t.removeAttribute(e)}(t,bt,e)}function r(t){return s(t,null),0}function u(t){return null===c(t)}function d(t){return c(t)===vt}function f(t,e,n,a){t&&(void 0===a?void 0===n?t(e):t(e,n):t(e,n,a))}function _(t,e){nt?t.classList.add(e):t.className+=(t.className?" ":"")+e}function v(t,e){nt?t.classList.remove(e):t.className=t.className.replace(new RegExp("(^|\\s+)"+e+"(\\s+|$)")," ").replace(/^\s+/,"").replace(/\s+$/,"")}function g(t){return t.llTempImage}function b(t,e){!e||(e=e._observer)&&e.unobserve(t)}function p(t,e){t&&(t.loadingCount+=e)}function h(t,e){t&&(t.toLoadCount=e)}function n(t){for(var e,n=[],a=0;e=t.children[a];a+=1)"SOURCE"===e.tagName&&n.push(e);return n}function m(t,e){(t=t.parentNode)&&"PICTURE"===t.tagName&&n(t).forEach(e)}function a(t,e){n(t).forEach(e)}function E(t){return!!t[st]}function I(t){return t[st]}function y(t){return delete t[st]}function A(e,t){var n;E(e)||(n={},t.forEach(function(t){n[t]=e.getAttribute(t)}),e[st]=n)}function k(a,t){var i;E(a)&&(i=I(a),t.forEach(function(t){var e,n;e=a,(t=i[n=t])?e.setAttribute(n,t):e.removeAttribute(n)}))}function L(t,e,n){_(t,e.class_loading),s(t,ut),n&&(p(n,1),f(e.callback_loading,t,n))}function w(t,e,n){n&&t.setAttribute(e,n)}function x(t,e){w(t,ct,l(t,e.data_sizes)),w(t,rt,l(t,e.data_srcset)),w(t,ot,l(t,e.data_src))}function O(t,e,n){var a=l(t,e.data_bg_multi),i=l(t,e.data_bg_multi_hidpi);(a=at&&i?i:a)&&(t.style.backgroundImage=a,n=n,_(t=t,(e=e).class_applied),s(t,ft),n&&(e.unobserve_completed&&b(t,e),f(e.callback_applied,t,n)))}function N(t,e){!e||0<e.loadingCount||0<e.toLoadCount||f(t.callback_finish,e)}function C(t,e,n){t.addEventListener(e,n),t.llEvLisnrs[e]=n}function M(t){return!!t.llEvLisnrs}function z(t){if(M(t)){var e,n,a=t.llEvLisnrs;for(e in a){var i=a[e];n=e,i=i,t.removeEventListener(n,i)}delete t.llEvLisnrs}}function R(t,e,n){var a;delete t.llTempImage,p(n,-1),(a=n)&&--a.toLoadCount,v(t,e.class_loading),e.unobserve_completed&&b(t,n)}function T(o,r,c){var l=g(o)||o;M(l)||function(t,e,n){M(t)||(t.llEvLisnrs={});var a="VIDEO"===t.tagName?"loadeddata":"load";C(t,a,e),C(t,"error",n)}(l,function(t){var e,n,a,i;n=r,a=c,i=d(e=o),R(e,n,a),_(e,n.class_loaded),s(e,dt),f(n.callback_loaded,e,a),i||N(n,a),z(l)},function(t){var e,n,a,i;n=r,a=c,i=d(e=o),R(e,n,a),_(e,n.class_error),s(e,_t),f(n.callback_error,e,a),i||N(n,a),z(l)})}function G(t,e,n){var a,i,o,r,c;t.llTempImage=document.createElement("IMG"),T(t,e,n),E(c=t)||(c[st]={backgroundImage:c.style.backgroundImage}),o=n,r=l(a=t,(i=e).data_bg),c=l(a,i.data_bg_hidpi),(r=at&&c?c:r)&&(a.style.backgroundImage='url("'.concat(r,'")'),g(a).setAttribute(ot,r),L(a,i,o)),O(t,e,n)}function D(t,e,n){var a;T(t,e,n),a=e,e=n,(t=It[(n=t).tagName])&&(t(n,a),L(n,a,e))}function V(t,e,n){var a;a=t,(-1<yt.indexOf(a.tagName)?D:G)(t,e,n)}function F(t,e,n){var a;t.setAttribute("loading","lazy"),T(t,e,n),a=e,(e=It[(n=t).tagName])&&e(n,a),s(t,vt)}function j(t){t.removeAttribute(ot),t.removeAttribute(rt),t.removeAttribute(ct)}function P(t){m(t,function(t){k(t,Et)}),k(t,Et)}function S(t){var e;(e=At[t.tagName])?e(t):E(e=t)&&(t=I(e),e.style.backgroundImage=t.backgroundImage)}function U(t,e){var n;S(t),n=e,u(e=t)||d(e)||(v(e,n.class_entered),v(e,n.class_exited),v(e,n.class_applied),v(e,n.class_loading),v(e,n.class_loaded),v(e,n.class_error)),r(t),y(t)}function $(t,e,n,a){var i;n.cancel_on_exit&&(c(t)!==ut||"IMG"===t.tagName&&(z(t),m(i=t,function(t){j(t)}),j(i),P(t),v(t,n.class_loading),p(a,-1),r(t),f(n.callback_cancel,t,e,a)))}function q(t,e,n,a){var i,o,r=(o=t,0<=pt.indexOf(c(o)));s(t,"entered"),_(t,n.class_entered),v(t,n.class_exited),i=t,o=a,n.unobserve_entered&&b(i,o),f(n.callback_enter,t,e,a),r||V(t,n,a)}function H(t){return t.use_native&&"loading"in HTMLImageElement.prototype}function B(t,i,o){t.forEach(function(t){return(a=t).isIntersecting||0<a.intersectionRatio?q(t.target,t,i,o):(e=t.target,n=t,a=i,t=o,void(u(e)||(_(e,a.class_exited),$(e,n,a,t),f(a.callback_exit,e,n,t))));var e,n,a})}function J(e,n){var t;et&&!H(e)&&(n._observer=new IntersectionObserver(function(t){B(t,e,n)},{root:(t=e).container===document?null:t.container,rootMargin:t.thresholds||t.threshold+"px"}))}function K(t){return Array.prototype.slice.call(t)}function Q(t){return t.container.querySelectorAll(t.elements_selector)}function W(t){return c(t)===_t}function X(t,e){return e=t||Q(e),K(e).filter(u)}function Y(e,t){var n;(n=Q(e),K(n).filter(W)).forEach(function(t){v(t,e.class_error),r(t)}),t.update()}function t(t,e){var n,a,t=i(t);this._settings=t,this.loadingCount=0,J(t,this),n=t,a=this,Z&&window.addEventListener("online",function(){Y(n,a)}),this.update(e)}var Z="undefined"!=typeof window,tt=Z&&!("onscroll"in window)||"undefined"!=typeof navigator&&/(gle|ing|ro)bot|crawl|spider/i.test(navigator.userAgent),et=Z&&"IntersectionObserver"in window,nt=Z&&"classList"in document.createElement("p"),at=Z&&1<window.devicePixelRatio,it={elements_selector:".lazy",container:tt||Z?document:null,threshold:300,thresholds:null,data_src:"src",data_srcset:"srcset",data_sizes:"sizes",data_bg:"bg",data_bg_hidpi:"bg-hidpi",data_bg_multi:"bg-multi",data_bg_multi_hidpi:"bg-multi-hidpi",data_poster:"poster",class_applied:"applied",class_loading:"litespeed-loading",class_loaded:"litespeed-loaded",class_error:"error",class_entered:"entered",class_exited:"exited",unobserve_completed:!0,unobserve_entered:!1,cancel_on_exit:!0,callback_enter:null,callback_exit:null,callback_applied:null,callback_loading:null,callback_loaded:null,callback_error:null,callback_finish:null,callback_cancel:null,use_native:!1},ot="src",rt="srcset",ct="sizes",lt="poster",st="llOriginalAttrs",ut="loading",dt="loaded",ft="applied",_t="error",vt="native",gt="data-",bt="ll-status",pt=[ut,dt,ft,_t],ht=[ot],mt=[ot,lt],Et=[ot,rt,ct],It={IMG:function(t,e){m(t,function(t){A(t,Et),x(t,e)}),A(t,Et),x(t,e)},IFRAME:function(t,e){A(t,ht),w(t,ot,l(t,e.data_src))},VIDEO:function(t,e){a(t,function(t){A(t,ht),w(t,ot,l(t,e.data_src))}),A(t,mt),w(t,lt,l(t,e.data_poster)),w(t,ot,l(t,e.data_src)),t.load()}},yt=["IMG","IFRAME","VIDEO"],At={IMG:P,IFRAME:function(t){k(t,ht)},VIDEO:function(t){a(t,function(t){k(t,ht)}),k(t,mt),t.load()}},kt=["IMG","IFRAME","VIDEO"];return t.prototype={update:function(t){var e,n,a,i=this._settings,o=X(t,i);{if(h(this,o.length),!tt&&et)return H(i)?(e=i,n=this,o.forEach(function(t){-1!==kt.indexOf(t.tagName)&&F(t,e,n)}),void h(n,0)):(t=this._observer,i=o,t.disconnect(),a=t,void i.forEach(function(t){a.observe(t)}));this.loadAll(o)}},destroy:function(){this._observer&&this._observer.disconnect(),Q(this._settings).forEach(function(t){y(t)}),delete this._observer,delete this._settings,delete this.loadingCount,delete this.toLoadCount},loadAll:function(t){var e=this,n=this._settings;X(t,n).forEach(function(t){b(t,e),V(t,n,e)})},restoreAll:function(){var e=this._settings;Q(e).forEach(function(t){U(t,e)})}},t.load=function(t,e){e=i(e);V(t,e)},t.resetStatus=function(t){r(t)},Z&&function(t,e){if(e)if(e.length)for(var n,a=0;n=e[a];a+=1)o(t,n);else o(t,e)}(t,window.lazyLoadOptions),t});!function(e,t){"use strict";function a(){t.body.classList.add("litespeed_lazyloaded")}function n(){console.log("[LiteSpeed] Start Lazy Load Images"),d=new LazyLoad({elements_selector:"[data-lazyloaded]",callback_finish:a}),o=function(){d.update()},e.MutationObserver&&new MutationObserver(o).observe(t.documentElement,{childList:!0,subtree:!0,attributes:!0})}var d,o;e.addEventListener?e.addEventListener("load",n,!1):e.attachEvent("onload",n)}(window,document);</script><script data-no-optimize="1">var litespeed_vary=document.cookie.replace(/(?:(?:^|.*;\s*)_lscache_vary\s*\=\s*([^;]*).*$)|^.*$/,"");litespeed_vary||fetch("/wp-content/plugins/litespeed-cache/guest.vary.php",{method:"POST",cache:"no-cache",redirect:"follow"}).then(e=>e.json()).then(e=>{console.log(e),e.hasOwnProperty("reload")&&"yes"==e.reload&&(sessionStorage.setItem("litespeed_docref",document.referrer),window.location.reload(!0))});</script><script data-optimized="1" type="litespeed/javascript" data-src="https://diginode.in/wp-content/litespeed/js/96d0e6d4ba93134cbdab615e06eb2824.js?ver=8fb56"></script><script>const litespeed_ui_events=["mouseover","click","keydown","wheel","touchmove","touchstart"];var urlCreator=window.URL||window.webkitURL;function litespeed_load_delayed_js_force(){console.log("[LiteSpeed] Start Load JS Delayed"),litespeed_ui_events.forEach(e=>{window.removeEventListener(e,litespeed_load_delayed_js_force,{passive:!0})}),document.querySelectorAll("iframe[data-litespeed-src]").forEach(e=>{e.setAttribute("src",e.getAttribute("data-litespeed-src"))}),"loading"==document.readyState?window.addEventListener("DOMContentLoaded",litespeed_load_delayed_js):litespeed_load_delayed_js()}litespeed_ui_events.forEach(e=>{window.addEventListener(e,litespeed_load_delayed_js_force,{passive:!0})});async function litespeed_load_delayed_js(){let t=[];for(var d in document.querySelectorAll('script[type="litespeed/javascript"]').forEach(e=>{t.push(e)}),t)await new Promise(e=>litespeed_load_one(t[d],e));document.dispatchEvent(new Event("DOMContentLiteSpeedLoaded")),window.dispatchEvent(new Event("DOMContentLiteSpeedLoaded"))}function litespeed_load_one(t,e){console.log("[LiteSpeed] Load ",t);var d=document.createElement("script");d.addEventListener("load",e),d.addEventListener("error",e),t.getAttributeNames().forEach(e=>{"type"!=e&&d.setAttribute("data-src"==e?"src":e,t.getAttribute(e))});let a=!(d.type="text/javascript");!d.src&&t.textContent&&(d.src=litespeed_inline2src(t.textContent),a=!0),t.after(d),t.remove(),a&&e()}function litespeed_inline2src(t){try{var d=urlCreator.createObjectURL(new Blob([t.replace(/^(?:<!--)?(.*?)(?:-->)?$/gm,"$1")],{type:"text/javascript"}))}catch(e){d="data:text/javascript;base64,"+btoa(t.replace(/^(?:<!--)?(.*?)(?:-->)?$/gm,"$1"))}return d}</script></body>
</html>

				
			

views/index.pug:

				
					doctype html
html
  head
    title= title
  body
    h1= message

				
			

app.js:

				
					require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const app = express();

// Connect to MongoDB
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('Connected to MongoDB'))
  .catch(err => console.error('Could not connect to MongoDB', err));

// Define User schema and model
const userSchema = new mongoose.Schema({
  name: String,
  email: String
});
const User = mongoose.model('User', userSchema);

// Middleware
app.use(express.json());
app.use(express.static('public'));
app.use((req, res, next) => {
  console.log(`${req.method} request for ${req.url}`);
  next();
});

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

app.get('/about', (req, res) => {
  res.send('About Page');
});

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

app.post('/users', async (req, res) => {
  const user = new User({
    name: req.body.name,
    email: req.body.email
  });
  await user.save();
  res.status(201).send(user);
});

app.get('/users', async (req, res) => {
  const users = await User.find();
  res.json(users);
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something went wrong!');
});

// Set view engine
app.set('view engine', 'pug');
app.set('views', './views');

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

				
			

Explanation:

  1. Environment Variables: The .env file contains the port number and MongoDB URI. The dotenv package loads these variables into the application.
  2. Static Files: The public/index.html file is served statically by Express.
  3. Template Engine: The views/index.pug file is a Pug template rendered by Express.
  4. Database Connection: The application connects to a MongoDB database using Mongoose.
  5. Middleware: The application uses middleware for logging requests, parsing JSON request bodies, and serving static files.
  6. Routes: The application defines several routes (/, /about, /template, /users).
  7. Error Handling: A middleware function handles errors that occur in the application.
  8. Starting the Server: The application starts the server on the specified port.

Running the Application:

Install Dependencies:

				
					npm install express mongoose pug dotenv

				
			

Start the Server:

				
					node app.js

				
			

Testing the Application

  • Navigate to http://localhost:3000 in your browser: You will see “Hello, World!”.
  • Navigate to http://localhost:3000/about in your browser: You will see “About Page”.
  • Navigate to http://localhost:3000/template in your browser: You will see the Pug template rendered with the message “Hello, Pug!”.
  • Navigate to http://localhost:3000/index.html in your browser: You will see the static HTML file.
  • Use Postman or similar tools to test the /users endpoint:
    • GET /users: Retrieve the list of users.
    • POST /users: Add a new user by sending a JSON payload with name and email fields.

Setting up an Express.js application involves several steps, from installing the necessary tools to creating a basic server, adding routes, implementing middleware, and connecting to a database. By following this guide, you should have a comprehensive understanding of how to set up and configure an Express.js application. This foundation will enable you to build scalable and maintainable web applications with ease. Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India