medusa-auth-facebook
v0.0.4
Published
A starter for Medusa plugins.
Maintainers
Readme
medusa-auth-facebook
Medusa v2 plugin that adds Facebook OAuth authentication routes, an Auth provider, and storefront helper utilities.
Plugin Overview
medusa-auth-facebook integrates Facebook OAuth into a Medusa v2 store authentication flow.
It provides:
- A custom Auth module provider (
facebook) that extends Medusa auth provider behavior. - Store API endpoints to start OAuth and process callback.
- Helper utilities for storefront apps to initiate login and handle callback responses.
- Redirect-or-JSON callback behavior for frontend flexibility.
This solves the problem of adding social login via Facebook while still issuing Medusa JWT auth tokens tied to Medusa auth identities.
Medusa Version
- Built for Medusa v2 (
@medusajs/framework/@medusajs/medusa2.12.4inpackage.json).
Installation & Setup
1) Install the package
npm install medusa-auth-facebookyarn add medusa-auth-facebook2) Register Facebook Auth provider in modules
import { defineConfig } from "@medusajs/framework/utils"
export default defineConfig({
modules: [
{
resolve: "@medusajs/medusa/auth",
options: {
providers: [
{
resolve: "medusa-auth-facebook/providers/facebook-auth",
id: "facebook",
options: {
clientID: "<FACEBOOK_APP_ID>",
clientSecret: "<FACEBOOK_APP_SECRET>",
callbackUrl: "http://localhost:9000/store/auth/facebook/cb",
scope: ["email", "public_profile"],
},
},
],
},
},
],
})3) Register plugin options in plugins
import { defineConfig } from "@medusajs/framework/utils"
export default defineConfig({
plugins: [
{
resolve: "medusa-auth-facebook",
options: {
facebook: {
clientId: "<FACEBOOK_APP_ID>",
clientSecret: "<FACEBOOK_APP_SECRET>",
callbackUrl: "http://localhost:9000/store/auth/facebook/cb",
scope: ["email", "public_profile"],
},
frontendUrl: "http://localhost:3000",
},
},
],
})4) Build / run
npx medusa plugin:build
npx medusa develop5) Database migrations
No plugin-specific models/migrations are implemented, so no additional migration step is required for this plugin itself.
Configuration (config.ts / plugin options)
The plugin validates and reads options from plugin registration (resolve-options.ts and config.ts).
Plugin Options (plugins[].options)
| Option | Type | Required | Default | Description |
|---|---|---|---|---|
| facebook.clientId | string | Yes | - | Facebook App ID used by plugin option validation and callback config resolution. |
| facebook.clientSecret | string | Yes | - | Facebook App Secret used by plugin option validation. |
| facebook.callbackUrl | string | Yes | - | OAuth callback URL. |
| facebook.scope | string[] | No | ["email", "public_profile"] | OAuth scopes for Facebook login. |
| frontendUrl | string | No | http://localhost:3000 (route fallback) | Frontend base URL for redirecting success/error callback flows. |
Auth Provider Options (modules[].options.providers[].options)
| Option | Type | Required | Default | Description |
|---|---|---|---|---|
| clientID | string | Yes | - | Facebook App ID used by provider service during OAuth token exchange. |
| clientSecret | string | Yes | - | Facebook App Secret used for OAuth token exchange and state generation. |
| callbackUrl | string | Yes | - | Redirect URI sent to Facebook OAuth. |
| scope | string[] | No | ["email", "public_profile"] | Requested Facebook permissions. |
⚠️ Note: There are two option shapes in code: plugin options use
clientId, provider options useclientID(capitalD). Both must be configured correctly in their respective Medusa config sections.
Complete Example
import { defineConfig } from "@medusajs/framework/utils"
export default defineConfig({
modules: [
{
resolve: "@medusajs/medusa/auth",
options: {
providers: [
{
resolve: "medusa-auth-facebook/providers/facebook-auth",
id: "facebook",
options: {
clientID: "123456789012345",
clientSecret: "fb_secret_xxx",
callbackUrl: "http://localhost:9000/store/auth/facebook/cb",
scope: ["email", "public_profile"],
},
},
],
},
},
],
plugins: [
{
resolve: "medusa-auth-facebook",
options: {
facebook: {
clientId: "123456789012345",
clientSecret: "fb_secret_xxx",
callbackUrl: "http://localhost:9000/store/auth/facebook/cb",
scope: ["email", "public_profile"],
},
frontendUrl: "http://localhost:3000",
},
},
],
})Environment Variables
No process.env.* access is used in the plugin source implementation under src.
| Variable | Purpose | Required | Example | |---|---|---|---| | None in implementation files | - | - | - |
⚠️ Note: You will typically pass secrets/URLs into Medusa config using environment variables in your application, but this plugin package itself does not directly read
process.env.
REST APIs / Routes
1) GET /store/auth/facebook
Initiates Facebook OAuth by calling Medusa Auth service authenticate("facebook", ...). Typically returns a redirect location to Facebook.
- Auth requirement: Store route; handler explicitly requires publishable key header.
- Required headers:
| Header | Type | Required | Description |
|---|---|---|---|
| x-publishable-api-key | string | Yes | Required by route logic before auth flow begins. |
- Request body: none
- Query params: optional
callback_urlmay be forwarded from request data into provider flow. - Success response: redirect to Facebook OAuth URL, or
{ token }JSON in immediate-success edge case. - Failure response: Medusa unauthorized/not-allowed errors.
curl -i "http://localhost:9000/store/auth/facebook" \
-H "x-publishable-api-key: pk_test_xxx"2) POST /store/auth/facebook
Alias to the same logic as GET /store/auth/facebook.
curl -i -X POST "http://localhost:9000/store/auth/facebook" \
-H "x-publishable-api-key: pk_test_xxx"3) GET /store/auth/facebook/cb
Processes OAuth callback (code, state), validates via Auth service, creates JWT token, then returns JSON or redirects to frontend.
- Auth requirement: Store callback route; requires publishable key via header or query.
Query Params
| Param | Type | Required | Description |
|---|---|---|---|
| code | string | Yes | OAuth authorization code from Facebook. |
| state | string | Yes | OAuth state for CSRF validation. |
| publishable_key | string | Conditionally | Used if x-publishable-api-key header is not present. |
| format | string | No | If json, route responds with JSON instead of redirect behavior. |
Headers
| Header | Type | Required | Description |
|---|---|---|---|
| x-publishable-api-key | string | Conditionally | Preferred publishable key source (header has priority). |
| accept | string | No | If contains application/json, route returns JSON response shape. |
Success Response
- JSON mode:
{ token, authIdentity }
- Redirect mode (default):
- Redirect to
${frontendUrl}/auth/callback?token=<JWT>
- Redirect to
Error Response
- JSON mode:
401with{ error, type: "authentication_error" }
- Redirect mode:
- Redirect to
${frontendUrl}/auth/error?error=<message>
- Redirect to
curl -X GET "http://localhost:9000/store/auth/facebook/cb?code=abc&state=xyz&format=json" \
-H "x-publishable-api-key: pk_test_xxx" \
-H "accept: application/json"4) POST /store/auth/facebook/cb
Alias to the same logic as GET /store/auth/facebook/cb.
curl -X POST "http://localhost:9000/store/auth/facebook/cb?code=abc&state=xyz&format=json" \
-H "x-publishable-api-key: pk_test_xxx" \
-H "accept: application/json"5) GET /admin/plugin
Simple plugin health/test route returning HTTP 200.
- Auth requirement: No explicit auth checks in handler; route is namespaced under
/admin. - Response: empty
200 OK.
curl -i "http://localhost:9000/admin/plugin"6) GET /store/plugin
Simple plugin health/test route returning HTTP 200.
- Auth requirement: No explicit auth checks in handler.
- Response: empty
200 OK.
curl -i "http://localhost:9000/store/plugin"Services
FacebookAuthProviderService
Located at src/providers/facebook-auth/service.ts; extends AbstractAuthModuleProvider.
It manages Facebook OAuth provider behavior for Medusa Auth module.
Key methods:
| Method | Signature | Description |
|---|---|---|
| authenticate | (data: AuthenticationInput, authIdentityProviderService) => Promise<AuthenticationResponse> | Generates OAuth state, stores state metadata, builds Facebook OAuth URL, and returns redirect location. |
| validateCallback | (data: AuthenticationInput, authIdentityProviderService) => Promise<AuthenticationResponse> | Validates callback params/state, exchanges code for token, fetches profile, retrieves/creates auth identity. |
| validateOptions (static) | (options: Options) => void | Throws Medusa invalid-data error if provider options are missing required fields. |
Helper utilities (storefront SDK-style helpers)
Located in src/helpers/facebook-auth.ts and src/helpers/base-client.ts.
| Function | Description |
|---|---|
| initiateFacebookLogin | Calls /store/auth/facebook, extracts redirect URL for frontend navigation. |
| handleFacebookCallback | Calls callback endpoint, extracts token from redirect URL or JSON response. |
| createFacebookAuthHelpers | Returns preconfigured helper methods for shared transport options. |
| buildHeaders, normalizeBaseUrl, getClientRequest | Transport/header/client utility functions for helper requests. |
Workflows & Steps (Medusa v2)
No custom workflows or steps are implemented.
Subscribers / Event Hooks
No event subscribers are implemented.
Admin UI / Widgets
No admin widgets, route injections, or admin UI extensions are implemented in code.
⚠️ Note:
src/adminonly contains starter scaffolding files (README, i18n placeholder, tsconfig, vite-env) and no actualdefineWidgetConfig/admin route extension implementation.
Models & Entities
No custom models/entities are defined by this plugin.
The plugin interacts with auth identity data through Medusa Auth services and provider metadata/user metadata.
Use Cases & Examples
Store customer social login via Facebook
- Use
GET /store/auth/facebookto start OAuth and redirect customer to Facebook.
- Use
Frontend callback token issuance
- Use
/store/auth/facebook/cbwithcodeandstateto receive a Medusa JWT token and sign in customer sessions.
- Use
JSON callback handling for SPA/API clients
- Call callback with
Accept: application/json(orformat=json) to avoid redirect parsing.
- Call callback with
Reusable storefront integration in Next.js/React
- Use
initiateFacebookLoginandhandleFacebookCallbackfrommedusa-auth-facebook/helpers.
- Use
SSR/server-side helper setup
- Use
createFacebookAuthHelpersto centralize base URL, publishable key, and client transport configuration.
- Use
Troubleshooting
Missing publishable key error
- Symptom: route rejects with message requiring
x-publishable-api-keyorpublishable_key. - Fix: always send
x-publishable-api-key; for callback redirects fallback topublishable_keyquery param.
Callback fails with missing code or state
- Symptom: invalid callback error.
- Fix: verify Facebook app callback URI and ensure frontend passes unmodified callback query parameters.
Invalid OAuth state
- Symptom: callback returns invalid state/authentication error.
- Fix: ensure callback is from the same initiated flow and state is not stale/tampered.
Redirect goes to localhost instead of production frontend
- Symptom: success/error callback redirects to
http://localhost:3000. - Fix: configure plugin
options.frontendUrlin Medusa config.
Provider not invoked
- Symptom: authenticate/validate callback fails for provider resolution.
- Fix: ensure Auth module includes provider registration with:
resolve: "medusa-auth-facebook/providers/facebook-auth"id: "facebook"
