EJS Express Nodejs Multi-page registration form- best way to store JSON over 2 pages

Viewed 575

I have a 2 page registration page in Express EJS:

/signup1 - username password /signup2 - firstname lastname

and they both have separate form fields with post buttons to create a registered user on my site.

app.post("/signup1", function(req, res) {

  const signupDetail1 = {
    username: req.body.username,
    password: req.body.password
};
res.render("signup2");
app.post("/signup2", function(req, res) {
const signupDetail2 = {
    firstName: req.body.firstName,
    lastName: req.body.lastName

//mongoose create registered user here with username password (from first page) and firstname //last name from second page

});

What is the best or easiest way to pass the request variables from the first login page to the second login page to post?

Thank you in advance for your help!

1 Answers

Hi @dthanny and welcome to stackoverflow :)

In this case I'd adivse against trying to pass the details from page 1 over to page 2, instead I'd suggest you store them on the server side after each step. I'm suggesting this for several reasons:

  1. For the information to be sent up with the second request as well, the frontend will need to hold the data somehow. It's quite common with Single Page Applications (using vue, react, angular, etc) to do multi-step forms and only send a single request after collecting all the info. In your case you're using server side rendering which means you'd need the frontend to store the info somehow, this could get quite messy and if you do decide to do it you might find that you open up some validation flaws.
  2. Presumably if the user enters data that goes against validation on stage 1 you'll want to ask them to re-enter it before moving onto stage 2. Since you've validated the data then, there is no reason not to store it immedietely.
  3. It will be much simpler to store the data and move onto the next step than to send the data back down to the client again, and have it re-send it on the final request.

It seems like it will be much simpler to just store the information after each step for you and will reduce the amount of code you need to write substantially.

If for some reason you cannot do this then I would suggest using some frontend javascript to collect all the information before sending it up rather than using the server side to drive the steps. If you use that approach then the data will never hit your server (a good approach if it's sensitive information).

Related