Search code examples
node.jsexpressstormpath

Stormpath Express: Save customData


I'm running an express server with express-stormpath for auth and to store same custom data about the user.

How can I post data to the server and save them to stormpath? Currently my post looks like this:

app.post('/post', stormpath.loginRequired, function(req, res) {
   var stundenplan_data = req.body;
   console.log(stundenplan_data);
   req.user.customData.stundenplan = stundenplan_data;
   req.user.customData.save();
});

I'm getting the right data I want to post in the console.log but if I call the data in another get request the custom data is empty.


Solution

  • I'm the author of the express-stormpath library, what I'd do is this:

    When you initialize Stormpath as middleware, add the following setting to automatically make customData available:

    app.use(stormpath.init(app, {
      ...,
      expandCustomData: true,  // this will help you out
    }));
    

    Modify your route code to look like this:

    app.post('/post', stormpath.loginRequired, function(req, res, next) {
      var studentPlan = req.body;
      console.log(studentPlan);
      req.user.customData.studentPlan = studentPlan;
      req.user.customData.save(function(err) {
        if (err) {
          next(err);  // this will throw an error if something breaks when you try to save your changes
        } else {
          res.send('success!');
        }
      });
    });
    

    The reason your changes weren't working above is that you didn't expand the customData first. Stormpath requires a separate request to 'grab' your customData, so if you don't do that first, things will fail to save.

    The above change ensures this happens for you automatically =)