npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

express-simple-google-authn

v1.0.4

Published

Express middleware / utility which enables easy user authentication through Google Identity Services, using OAuth 2.0 tokens.

Readme

💡 express-simple-google-authn

Basic middleware / utility for Express which enables easy user authentication through Google Identity Services, using OAuth2 tokens. Attempts to be useful for Single Page Applications that integrate a Sign In With Google button; especially prototypes, tools and alike.
A simple but complete supplementary frontend example is also included. Please see Usage for details.

High-level Flow

  • A Sign-in With Google button is rendered on your website, using Google Identity Services JavaScript API.
  • A user clicks on the button and goes through Google Account selection.
  • After a successful sign in, your frontend receives an ID Token from Google and forwards it to the route provided by this package.
  • The obtained short-lived ID Token is verified and a new long-lived JWT token is returned.
  • Your frontend can save the fresh JWT token and include as a header in any subsequent request which require authentication.

Disclaimer

This package is not connected to, affiliated with or endorsed by Google LLC in any way.

Prerequisites

Setting up is easy! All you need to get started is:

  • A Google Cloud Project. Create a new one if you don't have any.
  • A Web application OAuth Client ID. Create a new one if you don't have it yet: select Web application as your Application type.
    Remember to fill out the Authorised JavaScript origins section, even if you are just testing on localhost.
    FYI, the included example uses a http://localhost:8081 origin.

Usage

Backend (Express)

Using authentication in an Express server application:

const expressSimpleGoogleAuthn = require('express-simple-google-authn');

const {
    googleSignIn,
    googleUserVerify,
} = expressSimpleGoogleAuthn({
    'client_id': process.env.GOOGLE_CLIENT_ID,
    // For all available options, see the table below this sample.
});

// The provided `googleSignIn` route verifies a Google ID Token from the Authorization header and issues a new JWT token:
app.get('/google-sign-in', googleSignIn);

// Add the `googleUserVerify` middleware to any route that should require user authn:
app.get('/user', googleUserVerify, (request, response) => {
    response.json(request.google_user);
});

For the full code example and instructions on how to run the server using a single Docker command, please view example/backend/server.js in this package repository.

expressSimpleGoogleAuthn will accept the following parameters (all are optional except client_id): |name|is required?|type|default value|information| |---|---|---|---|---| |client_id|Yes|string|undefined|You can grab your Client ID from the Credentials screen In Google Cloud Console.| |hosted_domain|No|string|null|This option can be used to allow only specific G Suite users (provide your custom suffix as yourcompany.com, for example).| |request_user_prop_name|No|string|google_user|This middleware attaches the user data to request object so any subsequent handlers (like routes) can access it. Use this option if you need to change the name of the property.| |http_bad_request_code|No|integer|400|HTTP code to use for 'Bad Request' responses.| |http_unauthorized_code|No|integer|401|HTTP code to use for 'Unauthorized' responses.| |http_internal_error_code|No|integer|500|HTTP code to use for 'Internal Error' responses.| |log_exceptions|No|boolean|false|Whether to log caught and handled exceptions in console.| |jwt_lifespan_seconds|No|integer|604800|The lifespan of issued tokens in seconds. Defaults to one week.| |jwt_algo|No|string|HS256|The algorithm used to sign and verify JWT tokens. See the jsonwebtoken documentation for supported values.| |jwt_secret|No|string|buffer|object|KeyObject|crypto.randomBytes(32).toString('hex')|The secret passphrase or key used to sign JWT tokens. By default, an Ad-Hoc secret is automatically generated - please note it's not persistent and will be rotated on server restart (effectively logging the users out).|

Frontend

For the supplementary frontend example (framework agnostic), please view example/frontend/index.html provided in this package. It's a standalone application including necessary commentary and instructions on how to run.

<!-- Load Google Identity Services: -->
<!-- https://developers.google.com/identity/gsi/web/guides/overview -->
<script src='https://accounts.google.com/gsi/client'></script>

// Initialise Google Identity Services:
google.accounts.id.initialize({
    // Please remember to provide a real `client_id` (use same as for the Express middleware).
    'client_id': '???.apps.googleusercontent.com',
    // Handle Google flow completion:
    'callback': async (credentials_response) => {
        // Send the Google ID Token to our Express app:
        const id_token = credentials_response.credential;
        const response = await fetch('http://localhost:8080/google-sign-in', {
            'headers': {
                'Authorization': `Bearer ${id_token}`,
            },
        });

        // We should receive a fresh JWT token issued by our server:
        const jwt = await response.text();

        // https://pragmaticwebsecurity.com/articles/oauthoidc/localstorage-xss
        localStorage.setItem('identity', jwt);

        verifyUserCredentials();
    },
});

// Render the Google button:
// https://developers.google.com/identity/gsi/web/reference/js-reference#google.accounts.id.renderButton
const sign_in_with_google = document.getElementById('sign_in_with_google');
google.accounts.id.renderButton(sign_in_with_google, {
    'text': 'continue_with',
    'width': '280',
});

const verifyUserCredentials = async () => {
    // Authenticate the user with our stored JWT Token:
    const jwt_token = localStorage.getItem('identity');

    if (!jwt_token) {
        return;
    }

    const response  = await fetch(`http://localhost:8080/user`, {
        'headers': {
            'Authorization': `Bearer ${jwt_token}`,
        },
    });

    // If authentication was successful we'll receive decoded user information (as uid, email, name, etc.):
    const user = await response.json();
    console.log(user);
};

// Try to sign-in returning users when website loads:
verifyUserCredentials();

License

LICENSE.md

This package depends on google-auth-library (Apache 2.0 License) and jsonwebtoken (MIT License).

Contact

Please feel free to reach out if you'd like to provide feedback, contribute, or discuss your specific application:

📬 [email protected]