Conditional Routing Nodejs + Express

Conditional Routing Nodejs + Express
0.0 0

#1

Hi All,

This site is amazing and I am learning something new everyday!

I had one question (I am using Nodejs and Express):

Suppose I have 2 links. Each of these links leads to a unique form:

Link A --> (login form if not logged in) --> Form A

Link B --> (login form if not logged in) --> Form B

Upon clicking on these links, if the user is not logged in, I would like to redirect the user to the login page. Upon logging in, I would like the user to go to the correct page.

Is there a nice concise way to implement this? I had the following solution in mind:

Upon clicking on the link, redirect to a unique login page for each of the two links, which in turn redirects to the correct form page upon loggin in.

For example, clicking on Link A triggers a get request to “/login form/form A”. This then upon loggin redirects through a get request to “/form A”

This seems a bit long winded and repetitive.

Any guidance is much appreciated!


#2

There’s no need for extra get requests. You could set up a middleware to check for authentication

// middleware
const checkAuth = (req, res, next) => {

  if (authenticated) next()

 /**
 * not authenticated. So add the previous route
 * to the req object and redirect
 */
 req.session.returnTo = req.path
 res.redirect('/login')
}

// then check if you need to redirect in your login page

app.get('/login', (req, res) => {
  //... authenticate then...

  res.redirect(req.session.returnTo || 'default route')
 // reset req object
  delete req.session.returnTo
})

Here we take advantage of the fact that we can add items to an object, and that everything except primitives is an object in javascript.


#3

Brilliant, thanks a lot John really appreciate the logic outlined here!