• Сообщество
  • Блог
Документация
Плагины и интеграцииВсе расширения для Medusa от сообществаСтартерыЗапускайте проекты быстрее с готовыми решениями
ЭкспертыПодберите специалиста для разработки и развития вашего проекта на MedusaКейсыПосмотрите примеры Medusa в продакшене и успешные внедрения
Меч Moscow
Комплексная e-commerce платформа на Medusa для московского fashion-бренда

Меч Moscow · Fashion

Gorgo снижает затраты на адаптацию Medusa к локальным рынкам.

Мы разрабатываем плагины интеграции, осуществляем поддержку и развиваем сообщество разработчиков на Medusa в Telegram.

  • Ресурсы Medusa
  • Плагины и интеграции
  • Стартеры
  • Эксперты
  • Кейсы
  • Medusa Чат в Telegram
  • Medusa Новости в Telegram
  • Документация Gorgo
  • Связаться с нами
  • TelegramGitHub
Плагины
B

Better auth

Better Auth as the authentication engine for Medusa v2 — social OAuth, magic links, passkeys and 2FA for customers and admin users.

npm install @nualt/medusa-plugin-better-auth
Категория
Авторизация
Создано
Nualt
Версия
0.1.1
Последнее обновление
4 дня назад
Ежемесячные загрузки
Загрузка данных
Звезды на Github
1
npmNPMGitHubGithub

@nualt/medusa-plugin-better-auth

Better Auth as the authentication engine for Medusa v2 — social OAuth, email & password, magic links, passkeys and optional 2FA (via Better Auth plugins) for both customers and admin users, without touching Medusa's native session model.

How it works

Better Auth runs inside your Medusa server, mounted at , with its tables () in your Medusa Postgres. It handles every authentication flow. A Medusa auth module provider () then bridges the result: it validates the Better Auth session and lets Medusa issue its own native tokens for the requested actor ( or ). Your protected routes, the admin dashboard and your storefront keep working with standard Medusa auth.

Admin accounts are never created through OAuth: an identity is only linked to an existing invited admin user, and only when the provider verified the email.

Installation

pnpm add @nualt/medusa-plugin-better-auth better-auth
  1. Register the plugin and the auth provider in :
1module.exports = defineConfig({
2 // …
3 plugins: [
4 {
5 resolve: "@nualt/medusa-plugin-better-auth",
6 options: {
7 betterAuth: {
8 baseURL: process.env.BETTER_AUTH_URL, // public URL of this server
9 emailAndPassword: { enabled: true },
10 socialProviders: {
11 google: {
12 clientId: process.env.GOOGLE_CLIENT_ID!,
13 clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
14 },
15 },
16 // Any Better Auth option or plugin works here (magic link,
17 // passkey, 2FA, genericOAuth…). `database` and `basePath`
18 // are managed by the plugin.
19 },
20 // autoLink: "verified-email" (default) | "never"
21 },
22 },
23 ],
24 modules: [
25 {
26 resolve: "@medusajs/medusa/auth",
27 options: {
28 providers: [
29 { resolve: "@medusajs/medusa/auth-emailpass", id: "emailpass" },
30 {
31 resolve: "@nualt/medusa-plugin-better-auth/providers/better-auth",
32 id: "better-auth",
33 },
34 ],
35 },
36 },
37 ],
38})
  1. Set the environment variables:
1BETTER_AUTH_SECRET=<openssl rand -hex 32>
2BETTER_AUTH_URL=https://api.your-store.com
  1. Create the Better Auth tables. In development the plugin migrates automatically at boot ( defaults to true outside production). For production, run the migration during your deploy, from the directory you start Medusa from:
npx medusa-plugin-better-auth migrate

The command loads your , applies the Better Auth schema migrations to the configured database, and exits. It is idempotent, so running it on every deploy is safe.

The plugin requires Better Auth (the migration API moved to in 1.5.0); it is verified against 1.6.x.

Installing with npm

pnpm and yarn install this plugin without friction. npm's flat hoisting and strict peer resolution need two extra steps (verified on the official monorepo template, Medusa 2.17):

  1. Peer conflict at install — better-auth ships an optional peer chain () that pins , conflicting with the template's React 19. Install with:

    npm install @nualt/medusa-plugin-better-auth better-auth --legacy-peer-deps
  2. version clash at runtime — if an older (v4) ends up hoisted at your workspace root, the Better Auth OAuth module crashes with — and only once a social provider is configured, which makes it look like a provider bug. Fix: delete and , then reinstall (npm does not restructure a locked tree). Belt and braces, add to your root :

    1"overrides": {
    2 "better-auth": { "jose": "^6.1.0" },
    3 "@better-auth/core": { "jose": "^6.1.0" }
    4}

The plugin detects the crash at boot and prints this exact remedy. In an npm workspaces monorepo, install the plugin from the workspace root (hoisted): Medusa's module resolver looks the auth provider up from the root .

Zero-config providers

Set a pair of environment variables and the provider is live — button and brand icon included, on both the storefront helpers and the admin login widget:

socialProviders: socialProvidersFromEnv(),
ProviderEnvironment variables
Google /
Apple /
Facebook /
Microsoft /
Discord /
TikTok /
X (Twitter) /
GitHub /

An incomplete pair (ID without SECRET) is ignored with an explicit boot warning. Providers outside this list still work through the regular passthrough — merge them in manually:

socialProviders: { ...socialProvidersFromEnv(), zoom: { clientId, clientSecret } },

The UI helpers render a clean fallback (initial-letter badge) for any provider without a bundled brand icon.

Apple: is not a static secret but a signed JWT you generate from your Apple Developer key (six-month max lifetime). Generate it, then treat it as a regular env var.

Better Auth plugins from your Medusa config

compiles to CommonJS, but is ESM-only — a static import would crash at require time. Declare plugins lazily instead; the plugin resolves them with a dynamic import when the Better Auth instance is built:

1import { lazyBetterAuthPlugin } from "@nualt/medusa-plugin-better-auth/lib/lazy-plugins"
2
3betterAuth: {
4 plugins: [
5 lazyBetterAuthPlugin("magicLink", {
6 sendMagicLink: async ({ email, url }) => {
7 // send the email with your provider (Resend, SMTP…)
8 },
9 }),
10 ],
11}

The optional module specifier accepts an installed package name, an absolute path, or a URL. Relative paths such as are rejected because they would resolve from the plugin's compiled directory rather than from your Medusa project. The default module used above needs no extra configuration.

Magic link (passwordless)

Full recipe: enable the plugin as above, send the email (or log the link in dev), and point at your storefront page with the marker — the standard session exchange handles the rest. See the working implementation in nualt-shop ( and ).

Endpoints

EndpointPurpose
Every Better Auth flow (sign-in, callbacks, magic links…)
Configured methods (, , ), for building login UIs
Link the session identity to an existing customer (idempotent)
Link to an existing admin user (401 if none)
Exchange the session for a Medusa customer token (core route)
Exchange for an admin token (core route)

Storefront recipe (Next.js)

1import { createAuthClient } from "better-auth/react"
2import { magicLinkClient } from "better-auth/client/plugins"
3
4export const authClient = createAuthClient({
5 baseURL: `${BACKEND_URL}/better-auth`,
6 fetchOptions: { credentials: "include" },
7 plugins: [magicLinkClient()],
8})

Sign in with any Better Auth flow, then exchange the session:

  1. →
  2. First login only: with the token, then
  3. Use the final token like any Medusa customer JWT.

The storefront and backend must share a registrable domain (e.g. / ) so the browser sends the Better Auth session cookie cross-origin. Exchange calls must run in the browser (), not from a server runtime. The storefront origin must also be included in Medusa's env var because the core exchange routes (, ) live under and are gated by that policy.

See a complete implementation in nualt-shop ().

Ongoing hardening work and proposed follow-ups are recorded in the development tracker.

Admin dashboard

The plugin ships a widget: social buttons appear above the password form automatically for every configured social provider. Linking rules: the email must be verified by the provider and belong to an existing invited admin user.

Options

OptionDefaultDescription
— (required)Passthrough Better Auth config. and are managed by the plugin; core table names default to , , , .
Controls automatic identity linking for customers only: links when the provider verified the email; never links automatically. Admin linking is always explicit — an invited admin user must exist and the provider must have verified the email; has no effect on the route.
Run Better Auth schema migrations at boot.
Lowercase and trim new native Medusa customer/cart emails, resolve native logins case-insensitively, and reject registration when an active customer already exists with different casing.

Secret resolution: , else . The server refuses to boot without one. Caveat: in setups where the config module isn't loaded at plugin import time (some pnpm monorepos), the failure surfaces as a logged startup error and errors on instead of a hard boot refusal. A missing secret breaks email normalization too (it needs the resolved options); failures during Better Auth's own initialization after options resolved (e.g. the npm issue above) are scoped to only — email normalization and native Medusa customer/cart/emailpass flows keep working. Trusted origins are derived from your Medusa // and merged with any you provide.

Customer email normalization and guest orders

Heads up — this touches core Medusa routes. With enabled (the default), the plugin attaches middlewares to , , and the cart routes to canonicalize emails. This is the only place the plugin reaches outside , and it exists because case-duplicate accounts are a real-world footgun. Set to keep Medusa's native case-sensitive behavior untouched.

With enabled, the plugin applies one canonical email form to native Medusa customer registration, customer creation, and guest cart writes. Existing mixed-case identities remain usable: login first resolves the stored identity case-insensitively, then authenticates against its existing password hash.

An existing customer blocks another native registration with the same email under different casing. An existing guest customer () does not: Medusa deliberately keeps guest and registered customer records separate.

The plugin never merges guest orders automatically based on an email string. After login, expose Medusa's order-transfer flow to let the customer request a transfer () and confirm it using the token sent to the order email. This proves mailbox ownership before order data is attached to the account.

Production checklist

The plugin stays out of the hot path — Better Auth is only exercised at sign-in, after which clients hold native Medusa tokens — but the following must be configured before going live. Everything below is standard Better Auth configuration passed through the option.

Rate limiting across instances. Better Auth enables its rate limiter in production, but the default storage is in-memory, i.e. per instance. Behind a load balancer, switch to shared storage and tighten the sensitive endpoints:

1betterAuth: {
2 rateLimit: {
3 storage: "database", // or "secondary-storage" with Redis
4 customRules: {
5 "/sign-in/email": { window: 10, max: 3 },
6 "/sign-up/email": { window: 60, max: 5 },
7 },
8 },
9 // Behind a proxy/CDN, tell Better Auth where the client IP lives:
10 advanced: {
11 ipAddress: { ipAddressHeaders: ["cf-connecting-ip"] },
12 },
13}

Also rate-limit at your reverse proxy: the Medusa core exchange routes (, ) are not covered by Better Auth's limiter and each call costs a session lookup.

Cross-subdomain cookies. With a storefront on and the API on , configure (and keep on). This is the most common source of "works locally, fails in production" reports.

Postgres connections. The plugin runs its own pool (default max 10 per instance) next to Medusa's. The plugin owns this database option, so it cannot currently be tuned through ; size your database or pooler (pgbouncer) accordingly.

Session table growth. Expired rows are not purged eagerly; schedule a periodic cleanup ().

Migrations. Keep off in production and run during deploys.

License

MIT

Еще в этой категории

Посмотреть все
Авторизация
Passwordless logo

Passwordless

От Devx Commerce

Добавьте беспарольный вход по SMS

Загрузка данных
GitHubnpm
Авторизация
Keycloak logo

Keycloak

От Vymalo

Подключите безопасный вход через Keycloak и контроль доступа

Загрузка данных
GitHubnpm
Авторизация
WebAuthn logo

WebAuthn

От Vymalo

Включите беспарольную аутентификацию

Загрузка данных
GitHubnpm