/ Programming

How to add strong parameters in Node.js with Mongoose example

Strong parameters prevent users from maliciously updating attributes in the database that have not been whitelisted. With strong parameters, you will have to make a conscious decision of which attributes are allowed to be modified. It is a good security practice to only prevent users from accidentally modifying sensitive attributes.

This tutorial will show how to implement strong parameters in Node.js with examples using Express framework and Mongoose ORM. The style and convention is borrowed from Ruby on Rails and implemented the Node.js way.

Dependencies

For this, we'll use the params library which I have found to be to the simplest implementation.

npm install --save params

Route

This is how your update route would look like without any strong parameters. At this the point, the user is allowed to modify any parameters in your database.

const express = require('express');

const router = express.Router();

/* ... */

// Update user route
router.put('/:id', (req, res) => {
    User.findById(req.params.id, (err, user) => {
        user.set(req.body);
        user.save((saveErr, updatedUser) => {
            return res.send({ data: updatedUser });
        });
    });
});

Add strong parameters

First import the params dependency that was installed.

const express = require('express');
const params = require('params'); // Add this

const router = express.Router();

/* ... */

Just below, add the list of permitted params that you want to whitelist for the users to be able to modify.

/* ... */
const router = express.Router();

const permittedParams = ['firstName', 'lastName', 'email', 'bio', 'gender'];

The lastly, update the following in your update route. It filters fields in the request body that are not whitelisted with your strong parameters.

router.put('/:id', (req, res) => {
    User.findById(req.params.id, (err, user) => {
        user.set(params(req.body).only(permittedParams));
        user.save((saveErr, updatedUser) => {
            return res.send({ data: updatedUser });
        });
    });
});

Done

There you have it. The simplest solution to implementing strong parameters in Node.js. It is a good security practice that should be implemented much more. Hopefully, it gets to see more daylight.

Wei-Ming Thor

Wei-Ming Thor

I am a programmer based in Kuala Lumpur, Malaysia. I write guides on programming and running a software business.

Read More