JAVASCRIPT

Implementing Google OAuth 2.0 for User Login

Learn to integrate Google OAuth 2.0 into your Node.js application for user authentication, handling redirects and token exchange securely on the backend.

// server.js (using Express)
const express = require('express');
const axios = require('axios');
const querystring = require('querystring');
require('dotenv').config(); // Ensure your .env variables are loaded

const app = express();
const PORT = 3000;

const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID;
const GOOGLE_CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET;
const GOOGLE_REDIRECT_URI = 'http://localhost:3000/auth/google/callback';

// Step 1: Redirect user to Google for authentication
app.get('/auth/google', (req, res) => {
    const authUrl = 'https://accounts.google.com/o/oauth2/v2/auth?' +
        querystring.stringify({
            client_id: GOOGLE_CLIENT_ID,
            redirect_uri: GOOGLE_REDIRECT_URI,
            response_type: 'code',
            scope: 'profile email', // Requesting user profile and email
            access_type: 'offline', // To get refresh token
            prompt: 'consent' // To ensure refresh token is always returned
        });
    res.redirect(authUrl);
});

// Step 2: Google redirects back to your app, exchange code for tokens
app.get('/auth/google/callback', async (req, res) => {
    const { code } = req.query;

    if (!code) {
        return res.status(400).send('Authorization code missing.');
    }

    try {
        const tokenResponse = await axios.post('https://oauth2.googleapis.com/token',
            querystring.stringify({
                code: code,
                client_id: GOOGLE_CLIENT_ID,
                client_secret: GOOGLE_CLIENT_SECRET,
                redirect_uri: GOOGLE_REDIRECT_URI,
                grant_type: 'authorization_code'
            }),
            {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            }
        );

        const { access_token, id_token, refresh_token } = tokenResponse.data;

        // Optionally, fetch user info using the access_token
        const userInfoResponse = await axios.get('https://www.googleapis.com/oauth2/v3/userinfo', {
            headers: { Authorization: `Bearer ${access_token}` }
        });

        console.log('User Info:', userInfoResponse.data);
        console.log('Access Token:', access_token);
        // In a real app, store refresh_token securely and create a session for the user

        res.send(`<h1>Welcome, ${userInfoResponse.data.name}!</h1><p>You are logged in.</p>`);

    } catch (error) {
        console.error('Error during Google OAuth:', error.response ? error.response.data : error.message);
        res.status(500).send('Authentication failed.');
    }
});

app.get('/', (req, res) => {
    res.send('<h1>Home Page</h1><a href="/auth/google">Login with Google</a>');
});

app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
    console.log('Ensure GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET are set in your .env file.');
});
How it works: This Node.js Express snippet demonstrates integrating Google OAuth 2.0 for user authentication. It initiates the OAuth flow by redirecting the user to Google for consent. After the user approves, Google redirects back to `/auth/google/callback` with an authorization code. The server then exchanges this code for access and ID tokens with Google's token endpoint. Finally, it uses the access token to fetch user profile information, completing the login process.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs