Sling Academy
Home/Node.js/How to Retrieve the Full URL in Express JS

How to Retrieve the Full URL in Express JS

Last updated: December 28, 2023

Overview

Express.js, commonly referred to simply as Express, is a popular web application framework for Node.js designed to build websites, web applications, and APIs. One common task when working with Express is retrieving the full URL of a request. This can be important for logging, authentication, redirects, and more. Retrieving the full URL is simple but essential, and understanding how to do it can be invaluable in many scenarios.

In this article, we’ll look at several ways to retrieve the full URL in an Express.js application. We will begin with basic methods and gradually move to more advanced techniques to handle various use cases.

Basic Example: Using req.protocol, req.get(‘host’), and req.originalUrl

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

app.get('*', (req, res) => {
  const fullUrl = `
    <code>${req.protocol}://${req.get('host')}${req.originalUrl}</code>`;
  res.send(`Full URL: ${fullUrl}`);
});

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

This basic example demonstrates how to concatenate the protocol, host, and original URL to form the full URL within a wildcard GET route.

Using req.href in Middleware

app.use((req, res, next) => {
  req.fullUrl = `${req.protocol}://${req.get('host')}${req.originalUrl}`;
  next();
});

app.get('/example', (req, res) => {
  res.send('Full URL retrieved in middleware: ' + req.fullUrl);
});

Using middleware allows us to attach the full URL to the request object, making it available to all subsequent route handlers.

Advanced Example: Considering Proxies and Load Balancers

When behind a proxy or load balancer, such as Nginx, the req.protocol and req.get(‘host’) may not give the accurate result due to the client’s request being forwarded. Therefore, we need to trust the ‘X-Forwarded-*’ headers.

app.enable('trust proxy');

app.use((req, res, next) => {
  req.fullUrl = `${req.protocol}://${req.get('host')}${req.originalUrl}`;
  next();
});

By enabling ‘trust proxy’, Express knows to trust the headers set by the proxy for the original request information.

Generating Full URLs for API Responses

Sometimes, API endpoints need to return full URL references in their responses. Here’s a method to generate URLs dynamically:

app.get('/api/data', (req, res) => {
  const data = {
    userId: 1,
    resourceUrl: `${req.protocol}://${req.get('host')}/api/users/1`
  };
  res.json(data);
});

This practice is common for providing navigable links in API responses, often known as HATEOAS (Hypermedia as the Engine of Application State).

Conclusion

Understanding how to retrieve the full URL in an Express application is a small but crucial part of backend development. It’s a tool that’s useful in a variety of situations from debugging to creating reliable API services. Throughout this tutorial, we explored the basic, middleware-based, and proxy-aware methods for getting the full URL, along with making your API responses more dynamic and user-friendly with full URL paths. Apply these techniques as appropriate in your applications to enhance their functionality and reliability.

Next Article: How to Integrate H2 Database with Express and Node.js

Previous Article: Using res.end() and res.send() in Express JS

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