Integrating Facebook Login into Your Vue.js Typescript Application: A Step-by-Step Guide

Mirza Anees Baig Barlas
3 min readOct 9, 2024

--

First, you need to create a Facebook application to use the Facebook API:

  1. Go to Facebook Developers and log in.
  2. Click on “My Apps” > “Create App”.
  3. Fill in the necessary details and create your app.

Now go to your app and customize it check all the required details you need while login just as i selected email as well as public_profile

I am creating a vue ts project with vite just for example

Now Open in vs code and install dependencies

Now open index.html in root folder and in head section add script for fb sdk

<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js"></script>

Now create a component for FacebookLogin.vue and add this code for login with facebook

<template>
<button @click="loginWithFacebook">Login with Facebook</button>
<p>{{ status }}</p>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';

declare global {
interface Window {
fbAsyncInit: () => void;
FB: any;
}
}
const status = ref<string>('');
onMounted(() => {
window.fbAsyncInit = () => {
window.FB.init({
appId : 'Your_APP_ID', // Replace YOUR_APP_ID with your actual Facebook App ID
cookie : true,
xfbml : true,
version : 'v21.0' // Use the latest version available
});

window.FB.AppEvents.logPageView();
};

(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) { return; }
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
});
function loginWithFacebook(): void {
window.FB.login((response: any) => {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
window.FB.api('/me', { fields: 'name,email' }, (response: any) => {
console.log(`Good to see you, ${response.name}.`);
status.value = `Logged in as ${response.name}`;
console.log(response)
});
} else {
console.log('User cancelled login or did not fully authorize.');
status.value = 'Login failed';
}
}, { scope: 'email, public_profile' }); // only these two scopes can be used for testing before app is reviewed
}
</script>

Your page will look like this you can change it according to your requirements

Click Login and window for fb login will appear

So now you can see the user is logged in with facebook

Note: This tutorial contains the test implementation on dev server and you have to publish your facebook app first before testing it on production environment

Github repo: https://github.com/MaBbKhawaja/facebook-login-example

--

--

No responses yet