In this article, we are going to learn how to implement the Github Login in Node.js Application. We are using the Node.js Express Framework and Passport.js library for this tutorial.

Create a Github App For Your Application

Before proceeding further into coding got the GitHub login in node.js, first, we have to create an app in Github to get the client id and client secret which we will use in our passport.js configuration.

Go to the Github Developer page and login with your Github credentials and register a new OAuth application

Fill The details and click on the Register application button.

Application Name Fill the Name of your application here Homepage URL URL of your application landing page Application Description Description of the application Authorization callback URL Callback URL for the application. After successful login user will be redirected to this url of your application.



For this article use URL : http://localhost:3000/auth/github/callback

Get the Client Id and Client secret Of your Application.

Create Express App

We have got our client Id and client secret of our application. Now it’s time to do some coding in the node.js most famous express.js framework.

After setting up the express app, install passport, passport-facebook, ejs template npm libraries.

npm install passport passport-facebook ejs

After completing the above step, your app final structure should look like below

Directory Structure

Here, we are going to write our login into single file index.js but for building production-ready application you must avoid these things and use a proper node.js design pattern and modular architecture in your node.js application. This is only for educational purpose so that you have a clear idea on how to implement Github login in node.js application.

Views For the Github login in node.js

From the directory structure, we can see that there are two ejs file index.ejs and success.ejs in the views folder of the node.js application.

The index.ejs file is used to display the Github login link into our node.js application while success.ejs file will be used to display the user details after the successful Github login.

index.ejs file

Welcome To Github Social Login Demo <br> <a href="/auth/github"> Github Login </a>

success.ejs

Logged In Successfully. <% if (user) { %> <h2><%= user.name %></h2> <% } %> <a href="/auth/logout"> Log Out </a>

Routes of the Node.js Application

We have the following 5 routes in our application for the Github login implementation.

/ starting routes of the app. It display the login link /account User will be redirect to here after the successful github login in the application. /auth/facebook github login url for the app /auth/facebook/callback callback url which we gave into our github app earlier. This url will handle all the process of the github login in node.js application /auth/logout log out url of the application.

All the above mentioned routed are self-explanatory and easy to understand if you have already build any Node.js RESTful APIs earlier.

Index.js file of the application

This is the core file of the application which handles all the login of the Github login implementation.

import express from 'express'; import bodyParser from 'body-parser'; import cors from 'cors'; import passport from 'passport'; import path from 'path'; import { Strategy } from 'passport-github2'; let session = require('express-session'); /** passport setup */ passport.use(new Strategy({ clientID: 'GITHUB_APP_CLIENT_ID', clientSecret: 'GITHUB_APP_CLIENT_SECRET', callbackURL: "http://localhost:3000/auth/github/callback" }, function(accessToken, refreshToken, user, cb) { return cb(null,user); } )); passport.serializeUser(function(user, cb) { cb(null, user); }); passport.deserializeUser(function(obj, cb) { cb(null, obj); }); const app = express(); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); /** set app */ app.use(cors()); app.use(bodyParser.json({ limit: '50mb' })); //passport middleware app.use(session({ secret: 's3cr3t', resave: true, saveUninitialized: true })); app.use(passport.initialize()); app.use(passport.session()); app.use(express.static(__dirname + '/public')); const isAuthenticated = async (req, res, next) => { if (req.isAuthenticated()) { return next(); } res.redirect('/'); } app.get('/', (req, res) => { res.render('index'); }); app.get('/account', isAuthenticated, (req, res) => { res.render('success', { 'user' : req.user._json}); }); app.get('/auth/github', passport.authenticate('github', { scope: [ 'user:email' ] })); app.get('/auth/github/callback', passport.authenticate('github', { successRedirect: '/account', failureRedirect: '/' })); app.use('/auth/logout', (req, res) => { req.logout(); res.redirect('/'); }); app.listen(3000);

Let’s understand what the above code does although it is very easy to understand but let’s have a brief look. 🙂

From Line 1 to 8

import express from 'express'; import bodyParser from 'body-parser'; import cors from 'cors'; import passport from 'passport'; import path from 'path'; import { Strategy } from 'passport-github2'; let session = require('express-session');

Between lines 1 to 8, we are importing all the dependency of the project as we did in every express.js projects. There is nothing to explain here.

From Line 12 to 30

passport.use(new Strategy({ clientID: 'GITHUB_APP_CLIENT_ID', clientSecret: 'GITHUB_APP_CLIENT_SECRET', callbackURL: "http://localhost:3000/auth/github/callback" }, function(accessToken, refreshToken, user, cb) { return cb(null,user); } )); passport.serializeUser(function(user, cb) { cb(null, user); }); passport.deserializeUser(function(obj, cb) { cb(null, obj); });

Between these lines, we are configuring the passport.js library for the Github login. I already explain what is the use of serializeUser and deserializeUser in my previous article on facebook login implementation in node.js application.

From Line 32 to 52

const app = express(); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); /** set app */ app.use(cors()); app.use(bodyParser.json({ limit: '50mb' })); //passport middleware app.use(session({ secret: 's3cr3t', resave: true, saveUninitialized: true })); app.use(passport.initialize()); app.use(passport.session()); app.use(express.static(__dirname + '/public'));

Between these lines, we are setting up our express projects essentials things like passport, sessions, cors, body-parser, view engines etc. There is nothing to explain here if you are working in the express.js framework already.

From Line 55 to 58

const isAuthenticated = async (req, res, next) => { if (req.isAuthenticated()) { return next(); } res.redirect('/'); }

These lines contain the isAuthenticated function which checks if the user is already authorized or not to proceed further in the application.

From Line 60 to 75

app.get('/', (req, res) => { res.render('index'); }); app.get('/account', isAuthenticated, (req, res) => { res.render('success', { 'user' : req.user._json}); }); app.get('/auth/github', passport.authenticate('github', { scope: [ 'user:email' ] })); app.get('/auth/github/callback', passport.authenticate('github', { successRedirect: '/account', failureRedirect: '/' })); app.use('/auth/logout', (req, res) => { req.logout(); res.redirect('/'); });

Between these lines, we have routes of our app. For this tutorial, we have five routes as explained here.

Github Link

If you want the full source code for this then you can get that from the CodesQuery Github Profile.

Conclusion

That’s all about the Github login implementation in node.js application. This will give a brief idea on how Github login works and how you can use that in your node.js application.

You can also implement the facebook login strategy in your application which is much similar to the Github login implementation.

Hope this article helps you and if you have any doubt or suggestions then comment in the comment box and if you like this tutorial then please share it.