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 🙏

© 2026 – Pkg Stats / Ryan Hefner

medusa-google-login-logic

v1.0.1

Published

Ported Google Login logic from B&B_ui project.

Readme

Medusa Google Login Logic

The medusa-google-login-logic is a brand new library designed to handle Google OAuth authentication for MedusaJS applications. It is built to be modular, robust, and mirrors production-tested logic (ported from B&B_ui).

🏗 Architecture

The library is split into two layers:

  1. Service Layer (medusa-services/google-login.ts): Contains pure TypeScript functions for interacting with Medusa API and handling OAuth URL logic.
  2. Hook Layer (google-login-logic/src/hooks/useGoogleAuth.ts): A React hook that orchestrates the flow, manages state (loading, error), and handles UI events.

🛠 Core Logic Explanation

1. The Login Flow (login function)

When you call the login() function from the hook:

  • Base URL Detection: It automatically detects your storefront URL using environment variables (NEXT_PUBLIC_BASE_URL or NEXT_PUBLIC_MEDUSA_STOREFRONT_URL) or window.location.origin.
  • Production Routing: If it detects it's not on localhost and matches the productionDomain (default: bellyandbaby.co), it forces the use of the production URL.
  • URI Normalization: It ensures the redirect_uri sent to Google matches the Google Console exactly (handles trailing slashes and protocols).
  • Redirection: It calls the Medusa SDK to get the Google login location and redirects the user.

2. The Callback Flow (processCallback function)

The hook automatically detects the code in the URL (if queryParams are passed) and completes the login:

  • Token Exchange: Exchanges the Google authorization code for a Medusa authentication token.
  • Account Linking Check:
    • It decodes the token to check for actor_id.
    • If actor_id is missing, it means the Google account is not yet linked to a Medusa customer.
  • Automatic Customer Creation:
    • For new users, it automatically calls createCustomer using the email extracted from the Google token.
    • If the user already has an account but it's not linked, it handles the conflict gracefully and asks for a re-login (onNeedsReLogin).
  • Session Management: Automatically refreshes the token for existing customers to ensure a valid session and retrieves full customer data.

🚀 How to Use

1. In your Login Button

import { useGoogleAuth } from 'medusa-google-login-logic';

const GoogleLoginButton = ({ sdk }) => {
  const { login, isLoading, error } = useGoogleAuth({ sdk });

  return (
    <button onClick={login} disabled={isLoading}>
      {isLoading ? 'Redirecting...' : 'Continue with Google'}
    </button>
  );
};

2. In your Callback Page

import { useGoogleAuth } from 'medusa-google-login-logic';
import { useSearchParams, useRouter } from 'next/navigation';

const GoogleCallbackPage = ({ sdk }) => {
  const searchParams = useSearchParams();
  const queryParams = Object.fromEntries(searchParams.entries());
  const router = useRouter();

  const { isLoading, error, customer } = useGoogleAuth({
    sdk,
    queryParams, // Hook auto-triggers logic when queryParams.code exists
    onSuccess: (data) => {
       router.push('/account');
    },
    onError: (msg) => alert(msg),
    onNeedsReLogin: (email) => {
       // Typically happens after automatic account creation
       alert("Account created! Please login again with Google.");
       router.push('/login');
    }
  });

  if (isLoading) return <div>Authenticating...</div>;
  if (error) return <div>Error: {error}</div>;
  
  return <div>Welcome back!</div>;
};

⚙️ Setup for Other Projects

To use this library in a new project, follow these steps:

1. Installation

If your project is in the same mono-repo:

npm install ../path/to/medusa-google-login-logic

Or if published:

npm install medusa-google-login-logic

2. Required Environment Variables

Add these to your project's .env or .env.local:

  • NEXT_PUBLIC_MEDUSA_BACKEND_URL: Your Medusa backend URL.
  • NEXT_PUBLIC_BASE_URL: Your storefront URL (e.g., https://my-store.com).
  • NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY: Your Medusa publishable key.

3. Google OAuth Console Configuration

You MUST add your callback URL to the Authorized redirect URIs in your Google Cloud Console:

  • Local Development: http://localhost:8000/auth/customer/google/callback
  • Production: https://yourdomain.com/auth/customer/google/callback

[!IMPORTANT] Ensure the URL matches exactly (no trailing slash, matching protocol).

4. Code Implementation

Pass your configured Medusa SDK instance to the hook. The hook handles the rest.

import { Medusa } from "@medusajs/js-sdk";
import { useGoogleAuth } from "medusa-google-login-logic";

const sdk = new Medusa({
  baseUrl: process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL,
  publishableKey: process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY,
});

// Use in your components as shown in the examples above!