Bernardo
Bernardo

Reputation: 541

Express Set Session for Specific Routes

I am trying to include sessions only for some routes (the authentication ones) but I am having a problem because of the error page routes:

I have this:

    app.use(session({
        secret: config.secrets.session,
        saveUninitialized: false,
        resave: false,
        store: sessionStore,
        proxy: true,
        cookie: {
            maxAge: config.token_duration,
            secure: false
        }
        // rolling: false
    }));


    app.use('/api/user', require('./api/user'));
    app.use('/api/auth', require('./api/auth'));  

    app.route(['/error/500','/error/404','/user/settings'])
        .get((req, res) => {
            res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
        });

    app.route('/*/*')
        .get(errors[404]);       

    app.use(errors[500]); 

So, If I use it like this, all the pages in my application will create a session (which I don't want). If I move the session section after the error routes, I will never get to the api routes because it will reach the 404 route.

Thanks in advance

Upvotes: 2

Views: 8198

Answers (2)

newbreedofgeek
newbreedofgeek

Reputation: 3616

You can also chain/compose multiple middleware using Express.router() as mentioned in this example: Express: composing middleware

And then apply that composed router (of chained middleware) as a specific route handler.

Upvotes: 1

jfriend00
jfriend00

Reputation: 707328

Middleware can be associated with only certain routes and the order in which it is specified matters. There are a number of ways to do that and how to best implement it depends upon the paths your site uses and how you can most easily create a link between path and whether it should or should not have the session middleware on it.

One simple thing to do would be to put your error route handlers BEFORE your session middleware. Then, those route handlers would "handle" the request first and the session middleware would never get called.

app.route(['/error/500','/error/404','/user/settings'])
    .get((req, res) => {
        res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
    });

app.use(session({
    secret: config.secrets.session,
    saveUninitialized: false,
    resave: false,
    store: sessionStore,
    proxy: true,
    cookie: {
        maxAge: config.token_duration,
        secure: false
    }
    // rolling: false
}));

Other things you can do:

  1. Put a path on your session middleware so it is only invoked for certain paths in your site (all authenticated pages should be below that path).

  2. Create your own middleware handler that checks to see if the path is /error and if not, then it invokes the session middleware handler. If it is /error, then don't invoke the session middleware.

This last one could be done like this:

const sessionHandler = session({
    secret: config.secrets.session,
    saveUninitialized: false,
    resave: false,
    store: sessionStore,
    proxy: true,
    cookie: {
        maxAge: config.token_duration,
        secure: false
    }
    // rolling: false
});

app.use(function(req, res, next) {
    // if path does not start with /error/, then invoke session middleware
    if (req.url.indexOf("/error/") !== 0) {
        return sessionHandler(req, res, next);
    } else {
        next();
    }
});

Upvotes: 9

Related Questions