How to Get the Full URL in ExpressJS ?

When building web applications with Express.js, a popular framework for Node.js, there are many scenarios where you may need to retrieve the full URL of a request. This is especially useful for tasks like logging requests, generating absolute URLs for redirect responses, or creating links in response data. In this article, we will explore various methods to obtain the full URL in an Express.js application, including the use of built-in methods and constructing URLs manually.

Understanding URL Components

Before diving into how to retrieve the full URL, it’s essential to understand the different components that make up a URL:

  • Protocol: The method of access (e.g., http or https).
  • Host: The domain name or IP address (e.g., example.com).
  • Port: The server port number (e.g., 3000).
  • Path: The specific resource on the server (e.g., /api/users).
  • Query String: The parameters sent to the server (e.g., ?id=123).
  • Fragment: The anchor or section within a resource (e.g., #section1).

Express.js provides various tools to access these components, which can be combined to construct the full URL.

Problem statement

So that was pretty much about URL, now our problem statement is how to get that URL at the server? Because during the application in production, several times we need the Whole components of URL to understand the user requirements so that later server can fulfill them by sending a proper response.  

Approach

There is an easy and simple approach to solve this because directly or indirectly the user sends the request object and it contains sufficient information for the server. And we can extract essential properties from that object according to our needs. In this article, at step number 4, we are going to discuss how to construct the URL from this request object sent by the user.

Step 1:

Creating nodejs project and installing packages.

Step 2:

Create a nodejs application. As the whole operation is going to proceed with express framework hence it is the first compulsory step to create a node application.

npm init

Step 3:

This will ask you for few configurations about your project you can fill them accordingly, also you can change it later from the package.json file, you can use `npm init -y` for default initialization.

Step 4: Install express framework

npm install express

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"express": "^4.19.2",
}

Approach

  • Import express with require keyword and,
  • Then call the express() function provided by the express framework.
  • That function call will return our created app, store it in a const variable.
  • Set a PORT for your application 3000 is default but you can choose any other according to availability.
  • After then, call the listen() function, and with this our express server starts listening to the connection on the specified path.
  • The listen function takes port and callback function as an argument.

Example: The callback function provided as an argument gets executed either on the successful start of the server or it provides an error due to failure.

Node
// app.js 

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

// Do your task here, in this space.

app.listen(PORT, (error) => {       // Listen
    if (!error)
        console.log("Server is Successfully Running,
            and App is listening on port "+ PORT)
    else
            console.log("Error occurred, server can't start", error);
}
);

Step to Run Application: Run the application using the following command from the root directory of the project

node app.js

If yes, then you’ll receive something like this in your terminal, otherwise, In case your server is not starting, analyze the error and check syntax, etc and then restart the server.

Step 4: So now we will continue to create routes and finding the full URL of the request, But let’s first understand the parts of a URL. Below is the description and image which shows the structure of an URL. 

  • scheme: It is the protocol used to access the resource from the web, it may be HTTP or HTTPS, where ‘s’ stands for security, this scheme can be extracted by the .protocol property of request object like req.protocol.
  • host: This is the name of the place where all the files required for the server exist in reality. The name of the host can be extracted from the .hostname property from request objects like req.hostname.
  • port: It is the port number on which the server is listening, this port can be extracted directly in the server because we specify it before starts listening.
  • path This path determines the actual location of the file, page, resource been accessed, actually, you can think of it as a sub-address it can be extracted by the concatenation of (req.baseUrl + req.path).
  • query this query is used to provide some data before accessing the resources so that server can respond accordingly, it can be extracted by the req.query property of request objects.

Note: We don’t have to access the baseUrl, path, and query separately express provides us a property called req.originalUrl which contains everything after the hostname.   

The above example URL we are showing will be in your browser’s search bar when you click the algorithm section from the homepage of w3wiki.net

Example:

In this example, we are creating a route to receive user requests. We will use the following approach:

  • In the route provided below, we have specified a function on the ‘*’ path for GET method.
  • That’s because now we can send any URL from the browser to execute the given functionality.
  • After then we are simply accessing some properties of the request object,  objectName.propertyName this is one of the ways to extract data.
  • We have extracted 3 variables as protocol, hostname, and original URL.
  • In the next line, we are storing the port number which we have set earlier.
  • Later, We have created a URL string with template literals of ES6, the backticks are the way to create string templates and we can inject any javascript expression inside ${}.
  • In the end, the function send()  is simply returning the string as a response.
Node
// app.js 

app.get('*', function (req, res) {    
    const protocol = req.protocol;
    const host = req.hostname;
    const url = req.originalUrl;
    const port = process.env.PORT || PORT;

    const fullUrl = `${protocol}://${host}:${port}${url}`
    
    const responseString = `Full URL is: ${fullUrl}`;                       
    res.send(responseString);  
})


Step to run the application: Open the terminal and type the following command.

node app.js

Output:

Explanation:  When we enter any Url in the browser search bar, the browser sends a request object to the server in our case the server is a localhost. And Express catches all user requests at the provided route and inside the functionality of that route. The scheme http extracted from req.protocol, and hostname localhost is extracted from req.hostname and 3000 is being accessed from the PORT which we have set before running the server in step 3, and the remaining URL is being extracted from req.originalUrl.

Conclusion

Retrieving the full URL in an Express.js application is straightforward. By using req.protocol, req.get('host'), and req.originalUrl, you can construct the complete URL of incoming requests. This technique is useful for logging, redirects, or generating dynamic content based on the URL. By following the steps in this article, you can easily implement this functionality in your own Express.js applications.