medusa-google-login-logic
v1.0.4
Published
Ported Google Login logic from B&B_ui project.
Downloads
45
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:
- Service Layer (
medusa-services/google-login.ts): Contains pure TypeScript functions for interacting with Medusa API and handling OAuth URL logic. - 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_URLorNEXT_PUBLIC_MEDUSA_STOREFRONT_URL) orwindow.location.origin. - Production Routing: If it detects it's not on
localhostand matches theproductionDomain(default:bellyandbaby.co), it forces the use of the production URL. - URI Normalization: It ensures the
redirect_urisent 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.
- SDK Sync: Automatically synchronizes the token with the
sdk.clientinstance. - Immediate Login:
- Decodes the token to check for
actor_id. - If
actor_idis missing (new user), it callscreateCustomerand thenrefreshTokento "upgrade" the session immediately. - This allows new users to be logged in with a single flow, matching modern storefront behavior.
- Decodes the token to check for
- Persistence: Calls the
onPersistTokencallback after every successful token update to ensure the session is saved (e.g., to Cookies).
🚀 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
onPersistToken: async (token) => {
// Save the token to your storage/cookies
// This is called for both the initial token and refreshed tokens
await setSessionCookie(token);
},
onSuccess: (data) => {
// Only called once the user has a full session and actor_id
router.push('/account');
},
onError: (msg) => alert(msg),
});
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-logicOr if published:
npm install medusa-google-login-logic2. 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!