Social login allows users to sign in to your React app using their existing accounts with social platforms like Facebook, Twitter, Google, etc. This saves users the hassle of creating yet another account and password to remember. In this comprehensive guide, we will see how to enable social login in a React app.
Social login has become an essential feature for many web and mobile applications nowadays. It improves the new user onboarding experience by eliminating the registration form. Users can directly sign in with their existing social accounts in just one click.
Some key benefits of integrating social login in your React app are:
- Streamlined signup flow for users
- Higher conversion rates compared to traditional registration
- Access to user profile data from social platforms
- Better security than custom user management
The most popular social platforms used for social login include Facebook, Google, Twitter, GitHub, LinkedIn, etc. In this tutorial, we will see how to implement login with Facebook, Google and GitHub in a React application.
Pre-requisites
Before we start with the actual implementation, let’s look at some pre-requisites:
- Basic understanding of React concepts like components, props, state, hooks etc.
- Create React App setup on your local machine
- Basic knowledge of using React Router
- Account on Facebook for Developers, Google Cloud Console and GitHub Developer Settings for API keys
- Experience with making API calls in React
Make sure you cover the basics of React before diving into adding social login functionality. Having accounts on the respective developer platforms is also required to obtain the API keys.
Setting up the React App
Let’s start by creating a new React project using Create React App:
“`bash
npx create-react-app social-login-demo
“`
This will setup a boilerplate React app that we can build upon. Next, cd into the app directory and install React Router:
“`bash
cd social-login-demo
npm install react-router-dom
“`
We will use React Router to handle routing and navigation in the app. Now, open up App.js and let’s setup some basic routes:
“`jsx
import { BrowserRouter, Routes, Route } from ‘react-router-dom’;
function App() {
return (
);
}
export default App;
“`
This implements two sample routes for Homepage and Login page. We can now start building out these screens one by one.
Building the Homepage
Inside src folder, create a new component HomePage.js and add the following code:
“`jsx
export default function HomePage() {
return (
Home
Welcome to our social login demo app!
);
}
“`
This will render a simple homepage message for now. Next, we need to build the Login page.
Building the Login Page
Create a new component LoginPage.js with the following code:
“`jsx
import SocialLoginButtons from ‘./SocialLoginButtons’;
export default function LoginPage() {
return (
Login
);
}
“`
We have added a placeholder for rendering Social Login Buttons. Let’s now work on that component.
Adding Login Buttons
Create a new component SocialLoginButtons.js and add buttons for Facebook, Google and GitHub:
“`jsx
export default function SocialLoginButtons() {
return (
);
}
“`
These button components will trigger the respective social login flows. Let’s implement them one by one.
Facebook Login Button
The Facebook login button can be rendered using the React SDK provided by Facebook:
“`jsx
import { FacebookLoginButton } from ‘react-social-login-buttons’;
export default function FacebookLoginButton() {
return
}
“`
This will display the branded Facebook login button. The onClick handler will be invoked when the user clicks on it. We will replace this dummy alert with actual Facebook login logic later.
Google Login Button
For Google login, we can directly render a link button:
“`jsx
export default function GoogleLoginButton() {
return (
Sign in with Google
);
}
“`
This will render a simple text link for Google login. We’ll add styling and login logic later.
GitHub Login Button
The GitHub login button can be implemented similarly:
“`jsx
export default function GitHubLoginButton() {
return (
Sign in with GitHub
);
}
“`
With this, we have set up the placeholders for the social login buttons. Now we can move on to the actual implementation.
Implementing Facebook Login
To enable Facebook login in React app, we need to follow these steps:
- Register a Facebook App
- Install Facebook SDK
- Get App ID and App Secret
- Add Login Code
- Handle Authentication
- Fetch User Profile
- Handle Logout
Let’s go through each of these steps one by one:
1. Register a Facebook App
First, you need to register your app on Facebook for Developers platform to obtain app credentials. Follow these steps:
- Go to https://developers.facebook.com/ and login
- Click on My Apps > Create App
- Enter display name, contact email and category for your app
- Complete the security check and click on Create App
This will create a new Facebook app with App ID and App Secret which we’ll use later.
2. Install Facebook SDK
React apps can integrate with Facebook login using the javascript SDK provided by Facebook. Install the npm package:
“`bash
npm install react-facebook-login
“`
We can then import the required components in our app.
3. Get App ID and App Secret
In Facebook Developers console, click on Settings > Basic to get App ID and App Secret. We will need to configure these in our React app.
4. Add Login Code
Let’s update our FacebookLoginButton component to call the Facebook login dialog:
“`jsx
import FacebookLogin from ‘react-facebook-login’;
export default function FacebookLoginButton() {
const responseFacebook = (response) => {
console.log(response);
}
return (
);
}
“`
We initialize the FacebookLogin component with appId prop. The callback will be invoked on login.
5. Handle Authentication
When the user logs in, Facebook sends an access token and some user data in the callback response. We need to handle this response to authenticate the user:
“`jsx
const responseFacebook = (response) => {
if(response.accessToken) {
// Login success
// Authenticate user
} else {
// Login failed
}
}
“`
If access token is received, user has logged in successfully. We can authenticate the user on our backend server using this token.
6. Fetch User Profile
Once authenticated, we can make Graph API calls to fetch user profile data like name, email, profile pic etc:
“`jsx
const getUserProfile = async () => {
try {
const response = await axios.get(
`https://graph.facebook.com/me?fields=name,email,picture&access_token=${token}`
);
console.log(response.data);
// Update state
} catch(error) {
console.log(error);
}
}
“`
The user profile info can be used to create accounts or update existing accounts on the backend.
7. Handle Logout
For logging out users, we simply need to remove the stored access token:
“`js
const logout = () => {
window.FB.logout();
// Remove access token from storage
// Redirect to homepage
}
“`
This is how we can implement end-to-end Facebook authentication in a React app!
Implementing Google Login
To allow Google signup/login in React app, we need to:
- Create a Google Cloud project
- Get client ID and client secret
- Add Google Sign-In Button
- Initialize Google Auth SDK
- Trigger Google popup on click
- Handle client response
- Make API calls
Let’s go through the steps one by one:
1. Create a Google Cloud project
Create a new project on Google Cloud Console. Under Authentication section, choose OAuth Client ID. Select Web Application as the type.
2. Get client ID and client secret
In Credentials page, copy the Client ID and Client Secret. These will be used in our React app for authentication.
3. Add Google Sign-In Button
Let’s add a Sign-In with Google button in our GoogleLoginButton component:
“`jsx
export default function GoogleLoginButton() {
return (
);
}
“`
We’ll add styling and functionality next.
4. Initialize Google Auth SDK
Install the Google Auth library:
“`bash
npm install react-google-login
“`
Import and initialize it:
“`jsx
import { GoogleLogin } from ‘react-google-login’;
const clientId = YOUR_CLIENT_ID;
export default function GoogleLoginButton() {
return (
);
}
“`
5. Trigger Google popup on click
On clicking the button, the Google Auth popup will open up. Users can select their Google account here to sign in.
6. Handle client response
In onSuccess and onFailure callback handlers, we can process the response:
“`js
const responseGoogle = (response) => {
if(response.accessToken) {
// Login success
} else {
// Login failed
}
}
“`
If access token is received, that means login succeeded.
7. Make API calls
Once authenticated, we can make API calls to fetch user data:
“`js
const getUserData = () => {
const headers = {
‘Content-Type’: ‘application/json’,
Authorization: `Bearer ${accessToken}`
}
axios.get(‘https://www.googleapis.com/userinfo/v2/me’, {headers})
.then(response => {
console.log(response.data); //user profile info
})
.catch(error => {
console.log(error);
});
}
“`
This is how we can implement Google sign in with React. The user can be authenticated on backend and account can be created if not already exists.
Implementing GitHub Login
To allow logging in with GitHub, we need to follow these steps:
- Register a new OAuth app on GitHub
- Add GitHub Login Button
- Initialize GitHub API client
- Trigger GitHub login on click
- Handle redirect callback
- Fetch user data
- Log out user
Let’s understand each of these in detail:
1. Register a new OAuth App on GitHub
Create a new OAuth app on GitHub developer settings and configure the authorization callback URL.
2. Add GitHub Login Button
We already added a placeholder GitHub login button earlier. Now let’s add proper styling:
“`jsx
export default function GitHubLoginButton() {
return (
Sign in with GitHub
);
}
“`
3. Initialize GitHub API Client
Install the GitHub OAuth npm package:
“`bash
npm install react-github-login
“`
Import and initialize in our component:
“`jsx
import GitHubLogin from ‘react-github-login’;
const config = {
clientId: ‘YOUR_CLIENT_ID’,
scope: ‘user’
};
export default function GitHubLoginButton() {
return (
);
}
“`
This will setup the GitHub login client.
4. Trigger GitHub Login on Click
When the login button is clicked, it will open up the GitHub login popup. Users can authorize the app to sign in.
5. Handle Redirect Callback
Once the user authorizes, GitHub redirects back to the callback URL we configured earlier along with a temporary code. We need to handle this callback to continue the login flow:
“`jsx
const onSuccess = (response) => {
handleAuthorization(response.code);
};
const onFailure = (response) => {
console.log(response);
};
return (
);
“`
6. Fetch User Data
When the callback code is received, we can exchange it with the access token and fetch the user profile:
“`js
const getUserData = async (code) => {
const response = await axios.post(‘https://github.com/login/oauth/access_token’, {
client_id: ‘xxx’,
client_secret: ‘yyy’,
code: code
});
const accessToken = response.data.access_token;
const userResponse = await axios.get(‘https://api.github.com/user’, {
headers: {
Authorization: `Bearer ${accessToken}`
}
});
const userData = userResponse.data;
console.log(userData);
}
“`
The user profile information can then be used to login/register the user.
7. Log Out User
For logging out, we simply need to clear the access token from client storage. Optionally call GitHub revoke token API before logging user out.
This completes the GitHub login implementation! The user can now easily sign in using their GitHub account.
Conclusion
Implementing social login enhances the signup experience for users by allowing them to login with just one click using their existing accounts. We went through the steps to add login with Facebook, Google and GitHub in a React application.
Here are some key things to note when integrating social logins:
- Register apps on each platform developer console
- Handle authentication token on server for security
- Store tokens to persist user session across app reloads
- Call APIs to fetch user profile data
- Create new user or match with existing user on backend
With this, you should have a good understanding of how to add social login functionality in your React app!