How to Get Request URL in Express: Simple Guide
In Express, you can get the full request URL by combining
req.protocol, req.get('host'), and req.originalUrl. This gives you the complete URL the client requested inside your route handler.Syntax
To get the full request URL in Express, use these parts from the req (request) object:
req.protocol: The protocol used (http or https).req.get('host'): The host name and port.req.originalUrl: The path and query string.
Combine them like this: req.protocol + '://' + req.get('host') + req.originalUrl.
javascript
const fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
Example
This example shows a simple Express server that logs the full request URL when a client visits the root path.
javascript
import express from 'express'; const app = express(); const port = 3000; app.get('/', (req, res) => { const fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl; console.log('Full request URL:', fullUrl); res.send('Check your console for the full URL!'); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
Output
Server running at http://localhost:3000
Full request URL: http://localhost:3000/
Common Pitfalls
Some common mistakes when getting the request URL in Express include:
- Using
req.urlalone, which only gives the path and query, missing protocol and host. - Using
req.path, which excludes the query string. - Not considering proxies or HTTPS setups, which may require trusting proxy headers.
Always combine req.protocol, req.get('host'), and req.originalUrl for the full URL.
javascript
/* Wrong way: only path and query, no protocol or host */ app.get('/', (req, res) => { console.log(req.url); // outputs only '/' or '/?query=1' res.send('URL logged'); }); /* Right way: full URL */ app.get('/', (req, res) => { const fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl; console.log(fullUrl); // outputs full URL res.send('Full URL logged'); });
Quick Reference
Summary of useful req properties to get parts of the request URL:
| Property | Description | Example Value |
|---|---|---|
| req.protocol | Protocol used by the request | http or https |
| req.get('host') | Host name and port from headers | localhost:3000 |
| req.originalUrl | Original URL path and query string | /path?name=value |
| req.url | URL path and query (may be modified by middleware) | /path?name=value |
| req.path | URL path without query string | /path |
Key Takeaways
Use req.protocol + '://' + req.get('host') + req.originalUrl to get the full request URL in Express.
Avoid using req.url or req.path alone as they do not include protocol or host.
Remember to trust proxy headers if your app is behind a proxy to get correct protocol.
req.originalUrl includes the path and query string exactly as requested.
Logging the full URL helps debug and understand client requests clearly.