DEV Community

Cover image for How to use Google One Tap in your React or Vue project?
Burak Gür
Burak Gür

Posted on • Updated on

How to use Google One Tap in your React or Vue project?

Hi there,
I will show you how to use Google One Tap in your project. For this, i use my own npm package google-one-tap.

Alt Text

Get your Google API client ID

Open the "Credentials" page of the Google APIs console.
Create or select a Google APIs project. If you already have a Google Sign-In button, use the existing project and the web client ID.

1. Install package on your project.



npm install google-one-tap


Enter fullscreen mode Exit fullscreen mode

or



yarn add google-one-tap


Enter fullscreen mode Exit fullscreen mode

2. After this, import package.



import googleOneTap from 'google-one-tap';


Enter fullscreen mode Exit fullscreen mode

3. Use googleOneTap method with options.



const options = {
    client_id: '___CLIENT_ID___', // required
    auto_select: false, // optional
    cancel_on_tap_outside: false, // optional
    context: 'signin' // optional
};

googleOneTap(options, (response) => {
    // Send response to server
    console.log(response);
});


Enter fullscreen mode Exit fullscreen mode

Vue.js Full Code Example



import googleOneTap from 'google-one-tap';
export default {
    mounted() {
        const options = {
            client_id: '___CLIENT_ID___', // required
            auto_select: false, // optional
            cancel_on_tap_outside: false, // optional
            context: 'signin', // optional
        };
        googleOneTap(options, (response) => {
            // Send response to server
            console.log(response);
        });
    },
};


Enter fullscreen mode Exit fullscreen mode

After all this, you must send response to server.

Node.js Server Example



const { OAuth2Client } = require('google-auth-library');
const client = new OAuth2Client(CLIENT_ID);
async function verify() {
    const ticket = await client.verifyIdToken({
        idToken: token,
        audience: CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend
        // Or, if multiple clients access the backend:
        //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
    });
    const payload = ticket.getPayload();
    const userid = payload['sub'];
    // If request specified a G Suite domain:
    // const domain = payload['hd'];
}
verify().catch(console.error);


Enter fullscreen mode Exit fullscreen mode

Thanks for reading 😊

Top comments (0)