Express.js Tutorial for Building Node.js Web Applications

Express.js is a web application framework for Node.js. It provides a compact set of APIs for defining routes, processing HTTP requests, using middleware, serving files, and organizing web application code.

This Express.js tutorial introduces the framework through practical examples. You will learn how to install Express, create a server, define routes, process request data, use middleware, create modular routers, serve static files, and handle application errors.

What You Need Before Starting Express.js

  • Node.js and npm installed on your computer
  • Basic knowledge of JavaScript
  • A terminal or command prompt
  • A code editor such as Visual Studio Code

Check that Node.js and npm are available by running these commands.

</>
Copy
node --version
npm --version

Get Started with Express.js

The following tutorials provide an introduction to Express.js and explain how to install it with npm.

For a new project, Express should normally be installed as a local dependency from the project directory.

</>
Copy
mkdir express-app
cd express-app
npm init -y
npm install express

The installation command adds Express to the project’s dependencies in package.json.

Basic Express.js Web Server Example

The following example creates an Express application, defines a route for the root URL, and starts an HTTP server on port 8000.

</>
Copy
var express = require('express')

// create express application instance
var app = express()
 
// express route
app.get('/', function (req, res) {
   res.send('This is a basic Example for Express.js by TUTORIALKART')
})
 
// start server
var server = app.listen(8000)

In this code, require('express') loads the Express package. Calling express() creates the application object. The app.get() call registers a handler for GET requests sent to the URL path /. Finally, app.listen(8000) starts the server on port 8000.

Save the code in a file named app.js, then start the server from the project directory.

</>
Copy
node app.js

Open http://localhost:8000/ in a browser to view the response.

A more detailed example that explains how to create and run the application is available at Express.js Tutorial – Express.js Example Application.

Express.js Request and Response Objects

Every Express route handler receives request and response objects. The request object contains information sent by the client, while the response object provides methods for returning data.

  • req.params contains route parameters.
  • req.query contains query-string values.
  • req.body contains parsed request-body data when the appropriate middleware is enabled.
  • res.send() sends text, HTML, objects, or buffers.
  • res.json() sends a JSON response.
  • res.status() sets the HTTP response status.
</>
Copy
app.get('/status', function (req, res) {
  res.status(200).json({
    running: true
  })
})

Express.js Routes and HTTP Methods

An Express.js route connects an HTTP method and URL path to one or more handler functions. The following route handles GET requests sent to /hello/.

</>
Copy
// express route
app.get('/hello/', function (req, res) {
   res.send('This is a basic Example for Express.js by TUTORIALKART')
})

app is the Express application instance. The get method identifies the HTTP method, the first argument specifies the URL path, and the second argument is the route handler. The handler runs only when the incoming request method and path match the route.

Common Express route methods include app.get(), app.post(), app.put(), app.patch(), and app.delete().

</>
Copy
app.post('/users', function (req, res) {
  res.status(201).send('User created')
})

app.put('/users/:id', function (req, res) {
  res.send('User updated: ' + req.params.id)
})

app.delete('/users/:id', function (req, res) {
  res.send('User deleted: ' + req.params.id)
})

Detailed Express.js Tutorial on Routes – Express.js Routes.

Express.js Route Parameters and Query Strings

Route parameters identify variable parts of a URL path. A parameter is declared with a colon and read from req.params.

</>
Copy
app.get('/users/:id', function (req, res) {
  res.send('Requested user ID: ' + req.params.id)
})

A request to /users/42 sets req.params.id to 42.

Query-string values are available through req.query. For example, a request to /search?term=node provides the value node through req.query.term.

</>
Copy
app.get('/search', function (req, res) {
  res.send('Search term: ' + req.query.term)
})

Express.js Middleware and Request Processing

Middleware functions run during the request-response cycle. A middleware function can inspect or change the request and response objects, end the response, or call next() to continue to another middleware function or route handler.

</>
Copy
var express = require('express')
var app = express()
 
// define middleware function
function logger(req, res, next) {
   console.log(new Date(), req.url)
   next()
}
 
// calls logger:middleware for each request-response cycle
app.use(logger)

logger is a middleware function. It receives the current request, the response object, and a next function. Calling next() passes control to the next matching middleware function or route handler.

Middleware order matters. Express evaluates middleware and routes in the same order in which they are registered.

Complete Express.js Tutorial on Middleware – Express Middleware.

Parse JSON and Form Data in Express.js

Express includes middleware for parsing JSON request bodies and URL-encoded form submissions. Register these middleware functions before routes that use req.body.

</>
Copy
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

app.post('/profile', function (req, res) {
  res.json({
    received: req.body
  })
})

express.json() parses requests with JSON bodies. express.urlencoded() parses URL-encoded form data.

Express.js Router for Modular Route Files

Express Router is used to create independent router objects. A router can contain related routes and middleware, making it easier to divide a larger application into separate files.

The following router defines two user-related routes.

</>
Copy
var express = require('express')
var router = express.Router()

router.get('/', function (req, res) {
  res.send('User list')
})

router.get('/:id', function (req, res) {
  res.send('User ID: ' + req.params.id)
})

module.exports = router

The router can then be mounted in the main application.

</>
Copy
var userRouter = require('./routes/users')

app.use('/users', userRouter)

After mounting the router at /users, its root route responds to /users, and its parameter route responds to paths such as /users/42.

Serve Static Files with Express.js

The built-in express.static() middleware serves files such as HTML, CSS, JavaScript, and images from a directory.

</>
Copy
app.use(express.static('public'))

With this configuration, a file stored at public/css/style.css can be requested through /css/style.css.

Return HTML and JSON Responses in Express.js

Express can return several response types. Use res.send() for text or HTML and res.json() for JSON data.

</>
Copy
app.get('/html', function (req, res) {
  res.send('<h1>Express.js Application</h1>')
})

app.get('/api/message', function (req, res) {
  res.json({
    message: 'Hello from Express.js'
  })
})

Handle 404 Responses in Express.js

A 404 handler should be registered after all valid application routes. It runs only when no earlier route or middleware has completed the response.

</>
Copy
app.use(function (req, res) {
  res.status(404).send('Page not found')
})

Handle Express.js Application Errors

Error-handling middleware uses four parameters: err, req, res, and next. Register it after the application’s routes and other middleware.

</>
Copy
app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Internal server error')
})

For asynchronous operations, pass errors to next(err) so that Express can forward them to the error handler.

Use an Environment Variable for the Express.js Port

Local examples often use a fixed port. In hosted environments, the platform may provide a port through the PORT environment variable.

</>
Copy
var port = process.env.PORT || 8000

app.listen(port, function () {
  console.log('Server is running on port ' + port)
})

Complete Express.js Starter Application

The following example combines JSON parsing, middleware, routes, a 404 response, and error handling in one small application.

</>
Copy
var express = require('express')
var app = express()
var port = process.env.PORT || 8000

app.use(express.json())

app.use(function (req, res, next) {
  console.log(req.method + ' ' + req.url)
  next()
})

app.get('/', function (req, res) {
  res.send('Express.js application is running')
})

app.get('/api/status', function (req, res) {
  res.json({ status: 'ok' })
})

app.post('/api/messages', function (req, res) {
  res.status(201).json({
    message: req.body.message
  })
})

app.use(function (req, res) {
  res.status(404).json({ error: 'Route not found' })
})

app.use(function (err, req, res, next) {
  console.error(err)
  res.status(500).json({ error: 'Internal server error' })
})

app.listen(port, function () {
  console.log('Server is running on port ' + port)
})

Common Express.js Setup Problems

Express Cannot Be Found

If Node.js reports Cannot find module 'express', install Express from the directory containing the project’s package.json file.

</>
Copy
npm install express

Express Returns Cannot GET a Path

This response means no registered GET route matches the requested path. Check the path in the browser and confirm that the corresponding route is declared before the 404 handler.

The Express.js Port Is Already in Use

An address-in-use error means another process is already listening on the selected port. Stop the earlier process or configure the application to use another available port.

req.body Is Undefined

Register express.json() before JSON routes and express.urlencoded() before routes that process URL-encoded form data. Also confirm that the request uses the correct Content-Type header.

Express.js Tutorial FAQs

What is Express.js used for?

Express.js is used to build HTTP servers, web applications, REST APIs, middleware pipelines, and server-side application routes on Node.js.

Is Express.js a programming language?

No. Express.js is a JavaScript framework that runs on Node.js. JavaScript is the programming language, Node.js is the runtime, and Express provides web application APIs.

Should Express.js be installed globally?

Express should normally be installed locally in each project with npm install express. This records the dependency in package.json and keeps project installations reproducible.

What is the difference between app.use() and app.get()?

app.use() registers middleware and can match multiple HTTP methods. app.get() registers a route that handles only HTTP GET requests for the specified path.

Why must Express.js middleware call next()?

A middleware function calls next() when it has not completed the response and processing should continue. Omitting both a response and next() leaves the request waiting.

Express.js Tutorial Editorial QA Checklist

  • Confirm that Express is installed locally before running any example.
  • Verify that every route is declared before the 404 handler.
  • Check that middleware calling next() does not also send a second response.
  • Confirm that body-parsing middleware appears before routes that access req.body.
  • Verify that the browser URL and the port passed to app.listen() match.
  • Check that error-handling middleware uses all four parameters: err, req, res, and next.

Express.js Tutorial Summary

This Express.js tutorial covered project setup, server creation, routes, request and response objects, route parameters, query strings, middleware, body parsing, routers, static files, JSON responses, 404 handling, and application errors. These concepts provide the foundation for organizing larger Node.js web applications and APIs.