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:
- 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.
- Account Linking Check:
- It decodes the token to check for
actor_id. - If
actor_idis missing, it means the Google account is not yet linked to a Medusa customer.
- It decodes the token to check for
- Automatic Customer Creation:
- For new users, it automatically calls
createCustomerusing 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).
- For new users, it automatically calls
- 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-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!