Link Search Menu Expand Document

Broken Authorization in NodeJS


Node.js does not provide any native authentication and authorization mechanism that can be implemented using sessions. This task is often delegated to third-party frameworks and libraries.


Being a fairly low-level framework, Express.js does not provide ready-made authentication and access control mechanisms, but its middleware-based architecture can be easily leveraged to implement simple custom solutions.

As an example, consider the following administrative endpoint:

app.use('/admin', function (req, res) {
    res.end('some administrative functionality here...');

This endpoint can be accessed by anyone; Express.js allows a pipeline of stages that are processed in order to serve the actual content of the endpoint logic to be specified. For example, the following middleware checks that a session is established and that the current user is an administrator:

function check_admin(req, res, next) {
    const username = req.session.user_id;
    if (!username) {
    } else {
        const user = db.fetchUser(username);
        if (user.is_admin) {
            next(); // next middleware stage or handler
        } else {

Finally, the above logic can be plugged into every endpoint or router in order to enforce the access control mechanism:

app.use('/admin', check_admin, function (req, res) {
    res.end('some administrative functionality here...');


Using Express middleware