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-auth-facebook

v0.0.4

Published

A starter for Medusa plugins.

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/medusa 2.12.4 in package.json).

Installation & Setup

1) Install the package

npm install medusa-auth-facebook
yarn add medusa-auth-facebook

2) 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 develop

5) 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 use clientID (capital D). 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_url may 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>

Error Response

  • JSON mode:
    • 401 with { error, type: "authentication_error" }
  • Redirect mode:
    • Redirect to ${frontendUrl}/auth/error?error=<message>
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/admin only contains starter scaffolding files (README, i18n placeholder, tsconfig, vite-env) and no actual defineWidgetConfig/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

  1. Store customer social login via Facebook

    • Use GET /store/auth/facebook to start OAuth and redirect customer to Facebook.
  2. Frontend callback token issuance

    • Use /store/auth/facebook/cb with code and state to receive a Medusa JWT token and sign in customer sessions.
  3. JSON callback handling for SPA/API clients

    • Call callback with Accept: application/json (or format=json) to avoid redirect parsing.
  4. Reusable storefront integration in Next.js/React

    • Use initiateFacebookLogin and handleFacebookCallback from medusa-auth-facebook/helpers.
  5. SSR/server-side helper setup

    • Use createFacebookAuthHelpers to centralize base URL, publishable key, and client transport configuration.

Troubleshooting

Missing publishable key error

  • Symptom: route rejects with message requiring x-publishable-api-key or publishable_key.
  • Fix: always send x-publishable-api-key; for callback redirects fallback to publishable_key query 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.frontendUrl in 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"