Extending express (NodeJS)

Extending express

You want to add extra middleware to express or define your own route endpoints? Here we will explain you how you can do this.

Location

All custom code extending express are placed in extensions/server_connect/routes.

File Structure

Here is a sample of how such a file looks like.

exports.handler = function(app) {
  app.get('/hello', (req, res) => {
    res.send('Hello World');
  });
}

The module should export a handler method that accepts the express app as parameter. For the express API check https://expressjs.com/en/4x/api.html.

Login with Facebook Sample

To create a login with facebook we are going to use Passport.js which is a library for express to authenticate users. Documentation can be found at: http://www.passportjs.org/docs/facebook/.

First we will need to install passport and passport-facebook.

npm i passport passport-facebook

Next we are going to write our handler, we will create a file extensions/server_connect/routes/login.js with the following content:

const passport = require('passport');
const FacebookStrategy = require('passport-facebook').Strategy;

passport.use(new FacebookStrategy({
    clientID: FACEBOOK_APP_ID,
    clientSecret: FACEBOOK_APP_SECRET,
    callbackURL: "http://www.example.com/auth/facebook/callback"
  },
  function(accessToken, refreshToken, profile, done) {
    // Here you want to lookup or create the user in the database
    /* User.findOrCreate(..., function(err, user) {
      if (err) { return done(err); }
      done(null, user);
    }); */
  }
));

exports.handler = function(app) {
  // Redirect the user to Facebook for authentication.  When complete,
  // Facebook will redirect the user back to the application at
  //     /auth/facebook/callback
  app.get('/auth/facebook', passport.authenticate('facebook'));

  // Facebook will redirect the user to this URL after approval.  Finish the
  // authentication process by attempting to obtain an access token.  If
  // access was granted, the user will be logged in.  Otherwise,
  // authentication has failed.
  app.get('/auth/facebook/callback',
    passport.authenticate('facebook', {
      successRedirect: '/',
      failureRedirect: '/login'
    })
  );
};

You need to replace FACEBOOK_APP_ID and FACEBOOK_APP_SECRET with the App ID and App Secret from Facebook. In the callback url you need to replace http://www.example.com with your own domain.

After authentication in the callback function you want to search the user in your database or create it when it doesn’t exist. You can also add extra scopes to get access to the users data or post using his account. For this you will need the accessToken that is returned to call the Facebook API with it.

At last you need to add a link or a button on your page for your user to login like:

<a href="/auth/facebook">Login with Facebook</a>
Community Page
Last updated: