Sling Academy
Home/Node.js/Express.js: The Difference Between app.use() and app.get()

Express.js: The Difference Between app.use() and app.get()

Last updated: December 28, 2023

Overview

Express.js is a popular web server framework for Node.js, designed to make the task of building robust web applications and APIs more accessible. Within Express.js, app.use() and app.get() are two fundamental methods that handle the middleware and routes, respectively. This article provides a deep dive into how they differ, with code examples ranging from basic usage to more nuanced cases where their differences truly shine.

Understanding app.use()

Let’s start with app.use(). This method is used to mount middleware functions at specified path routes. When a request matches the path, the provided function(s) are executed in the order they are added. Middleware functions have the capability to execute code, modify the request and response objects, end the request-response cycle, and call the next middleware in the stack.

Code Example: Basic Middleware Registration with app.use()

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

app.use('/path', (req, res, next) => {
  console.log('Request received at /path');
  next();
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Understanding app.get()

On the other hand, app.get() is a method specifically for defining routes that listen to GET requests. You use app.get() to respond to requests at a particular route path with a single callback function (or a series of functions) that handle the request and produce the response.

Code Example: Basic Route Definition with app.get()

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

app.get('/path', (req, res) => {
  res.send('Response to GET request at /path');
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

More Advanced Examples

As you dive deeper into Express.js, you may encounter more complex scenarios where knowing the difference between app.use() and app.get() makes a significant impact on how you structure your application. For example, let’s look into error handling, parameterized paths, chaining middleware, and setting up a mixed stack of routes and middleware.

Error Handling with app.use()

In Express, you can create error-handling middleware that catches any errors thrown in preceding routes or middleware.

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

app.get('/', (req, res) => {
    throw new Error('Something went wrong!');
});

// Error handling middleware
app.use((err, req, res, next) => {
    console.error(err);
    res.status(500).send('Internal Server Error');
});

app.listen(3000);

Chaining Middleware

Chain multiple middleware functions to create a pipeline for request handling. This is useful for adding layers of functionality like logging, authentication, and data validation.

function logger(req, res, next) {
    console.log(`${req.method} ${req.url}`);
    next();
}

function authenticator(req, res, next) {
    // Authentication logic
    next();
}

app.use(logger);
app.use(authenticator);

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

Mixed Stack of Routes and Middleware

You can mix routes and middleware to handle complex application structures. For example, grouping routes and applying specific middleware to them.

const router = express.Router();

// Middleware specific to this router
router.use((req, res, next) => {
    // Perform some operations
    next();
});

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

// Apply the router
app.use('/', router);

Conclusion

In summary, app.use() is the middleware Swiss knife capable of handling requests at any HTTP method through a specified path, while app.get() explicitly handles GET requests to defined routes. By understanding their differences and leveraging them appropriately, you can structure your Express.js applications for better readability, maintainability, and functionality.

Next Article: Node.js & Express: Implementing Route Guards with Middleware (3 Ways)

Previous Article: How to Download a File from NodeJS Server using Express

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates