Josh Smith
Josh Smith

Reputation: 15028

Handling redirection in ExpressJS while avoiding redirect loop

This is my first time using Express' app.all(). When a user signs up through an outside oAuth provider, I still need them to provide an email after returning to the site. I'm basically setting them as inactive in the database and checking for req.session.active.

What I'm doing is

app.all('*', function(req, res, next) {
    if(!req.session.active) {
        if(req.path == '/complete_signup') {
            next();
        } else {
            return res.redirect('/complete_signup');            
        }
    }
});

But this doesn't seem to be working. How can I correctly check if the user is already redirected?

If you can suggest a method other than app.all(), that would work, too.

EDIT:

On second look, this is working, but none of the external resources (stylesheets, javascripts, etc.) seem to be loading since they don't match req.path.

Upvotes: 1

Views: 1121

Answers (1)

user3586413
user3586413

Reputation:

You can use the express-redirect-loop middleware (which uses sessions since HTTP Referrer header is unreliable). This will only work for requests that support cookie storage/jar (e.g. browser).

const express = require('express');
const session = require('express-session');
const redirectLoop = require('express-redirect-loop');

const app = express();

app.use(
  session({
    secret: 'test',
    resave: false,
    saveUninitialized: true
  })
);

app.use(redirectLoop());

app.get('/', (req, res) => res.sendStatus(200));
app.get('/bar', (req, res) => res.redirect('/foo'));
app.get('/foo', (req, res) => res.redirect('/foo'));
app.get('/baz', (req, res) => res.redirect('/bar'));

app.listen(3000);

Upvotes: 1

Related Questions