'Difference between req.url and req.originalUrl in Express.js version 4
I am trying to implement login feature in Express.js version 4 app. I need to determine whether an user is logged in before he can do certain actions. So I have a middleware called as isLoggedIn
which solely checks if user object is in session, if not, the user is redirected to login page. After the user successfully logs in, he must be redirected to the original URL.
app.get('/someaction', isLoggedIn, 'actual function to be executed');
Now inside isLoggedIn
method, I see that req.url
and req.originalUrl
contains the requested action. However if the user is not logged in, when redirected to /login
page, both req.url
and req.originalUrl
has /login
as the contents. From what I read here, I can override req.url for internal routing purposes. But in my case both req.url
and req.originalUrl
gets overridden by /login
action.
What am I doing wrong?
Solution 1:[1]
From the Express.js documentation:
req.url
is not a native Express property, it is inherited from Node’shttp
module.This property is much like
req.url
; however, it retains the original request URL, allowing you to rewritereq.url
freely for internal routing purposes. For example, the “mounting” feature ofapp.use()
will rewritereq.url
to strip the mount point.
In other words, req.url
might be overwritten during the internal routing, while req.originalUrl
will remain untouched.
Solution 2:[2]
The problem is that there are actually two entirely separate requests coming in to your server. The request for the /login
page doesn't know anything about the page that the client requested before that. So when you redirect to the /login
page, you need to save information about the originally-requested URL somewhere. I know of 2 solutions:
Some fancy work with session states allowing you to save the original URL as a variable, probably using promises.
Add the original URL as a query parameter to the
/login
request.
Check out this answer: How do I find original request path before redirect Express 4
Solution 3:[3]
You could achieve user redirection post login to the originally requested Url by using expression-session.
Steps:
At the time when isLoggedIn middleware is run you should capture req.originalUrl to req.session variable e.g. req.session.returnToUrl = req.originalUrl.
Upon authentication you can check if returnToUrl is set and otherwise set redirection Url to any default value you prefer. const redirectUrl = req.session.returnToUrl || "/anyOtherUrl";
After login redirect user to the Url using res.redirect(redirectUrl)
Credit to DevSprout and Colt Steele. A more detailed answer is available here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mike |
Solution 2 | Community |
Solution 3 | Karolis |