res.redirect('back') with parameters res.redirect('back') with parameters express express

res.redirect('back') with parameters


Using the referer header to find what page your user came from might be helpful:

app.get('/mobileon', function(req, res){  backURL=req.header('Referer') || '/';  // do your thang  res.redirect(backURL);});

You might also want to store backURL in req.session, if you need it to persist across multiple routes. Remember to test for the existence of that variable, something like: res.redirect(req.session.backURL || '/')


edit: Since my answer has been getting some upvotes I typed up my current way to do this. It got a little long so you can view it at https://gist.github.com/therealplato/7997908 .

The most important difference is using an explicit 'bounce' parameter in the query string that overrides the Referer url.


A really easy way of implementing this is to use connect-flash, a middleware for express that leverages the session middleware built into express to pass 'flash' messages to the next request.

It means you don't need to add fields to track urls or messages to the form or route patterns for your views.

It provides a simple version of the same feature in Ruby on Rails.

(obviously you have to be using the Express framework for this to use, but I highly recommend that too!)

Plug it in like this:

var flash = require('connect-flash');var app = express();app.configure(function() {  app.use(express.cookieParser('keyboard cat'));  app.use(express.session({ cookie: { maxAge: 60000 }}));  app.use(flash());});

And then use it like this:

app.get('/flash', function(req, res){  req.flash('info', 'Flashed message')  res.redirect('/');});app.get('/', function(req, res){  res.render('index', { message: req.flash('info') });});


If you're using sessions, you can just add that reg_error object to the req.session object before your redirect. Then it will be available on the req.session object when you're loading the previous page.