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

Меч Moscow · Fashion

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

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

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

npm install @xbstracts/medusa-supertokens
Категория
Авторизация
Создано
Xbstracts
Версия
0.0.2
Последнее обновление
21 час назад
Ежемесячные загрузки
Загрузка данных
Звезды на Github
0
npmNPMGitHubGithub

@patiparnne/medusa-supertokens

A Medusa v2 authentication provider plugin that enables session-based authentication using SuperTokens as the identity provider. Compatible with SuperTokens free tier (no OAuth2 license required).

Features

  • Direct session token verification with SuperTokens Core
  • Works with SuperTokens free tier (no paid features required)
  • Supports all SuperTokens authentication methods (Email/Password, Passwordless/OTP, Social Login)
  • Legacy CRM profile integration (refreshes profile data on every auth)
  • Email verification enforcement (optional)
  • Seamless integration with Medusa's auth module

Architecture Overview

1┌─────────────────┐ ┌─────────────────────┐ ┌─────────────────┐
2│ Storefront │ │ hisher-auth │ │ SuperTokens Core│
3│ (Next.js) │ │ (Backend API) │ │ (Database) │
4│ localhost:3000 │ │ localhost:4002 │ │ localhost:3567 │
5└────────┬────────┘ └──────────┬──────────┘ └────────┬────────┘
6 │ │ │
7 │ 1. Login (OTP/Social) │ │
8 │ ───────────────────────>│ │
9 │ │ 2. Create session │
10 │ │ ────────────────────────>│
11 │ 3. Access token │ │
12 │ <───────────────────────│ │
13 │ │ │
14 │ 4. POST /auth/customer/supertokens │
15 │ ─────────────────────────────────────┐ │
16 │ │ │
17 │ ┌─────────────────┴─────────────┴─────┐
18 │ │ Medusa Backend │
19 │ │ localhost:9000 │
20 │ │ │
21 │ │ 5. Verify token via /profile/ │
22 │ │ verify-token (hisher-auth) │
23 │ │ 6. Get user info & metadata │
24 │ │ 7. Create/retrieve auth identity │
25 │ └─────────────────────────────────────┘
26 │ │
27 │ 8. Medusa JWT token │
28 │ <────────────────────────────────────┘

Port Configuration (His & Her Project)

ServicePortDescription
Storefront3000Next.js storefront app
SuperTokens Core3567SuperTokens database/core service
hisher-auth Backend4002SuperTokens backend API with OTP/profile routes
hisher-auth Frontend4003SuperTokens demo UI (optional, for testing)
Medusa Backend9000Medusa e-commerce API

Note: The hisher-auth frontend (port 4003) is a SuperTokens demo UI showing buttons like "Continue to Store", "Call API", "Logout". It's NOT an admin dashboard - it's designed for authenticated users to test the session. You don't need to run it for production.

Prerequisites

  • Medusa v2.x
  • SuperTokens Core running (self-hosted via Docker or managed)
  • SuperTokens Backend API (hisher-auth) running
  • Storefront configured to redirect to hisher-auth for login

Installation

1npm install @patiparnne/medusa-supertokens
2# or
3yarn add @patiparnne/medusa-supertokens

Configuration

1. Configure Medusa

Add the plugin to your :

1import { defineConfig } from '@medusajs/framework/utils';
2
3module.exports = defineConfig({
4 // ... other config
5 modules: [
6 {
7 resolve: "@medusajs/medusa/auth",
8 options: {
9 providers: [
10 // SuperTokens Authentication Provider
11 {
12 resolve: "@patiparnne/medusa-supertokens/providers/supertokens-auth",
13 id: "supertokens",
14 options: {
15 // SuperTokens Core URL (for direct session verification)
16 coreUrl: process.env.SUPERTOKENS_CORE_URL || "http://localhost:3567",
17
18 // hisher-auth Backend API URL (for profile enrichment)
19 apiDomain: process.env.SUPERTOKENS_API_DOMAIN || "http://localhost:4002",
20
21 // API base path (default: '/auth')
22 apiBasePath: process.env.SUPERTOKENS_API_BASE_PATH || "/auth",
23
24 // SuperTokens Core API key (if configured)
25 apiKey: process.env.SUPERTOKENS_API_KEY,
26
27 // Callback URL for redirects (your storefront)
28 callbackUrl: process.env.SUPERTOKENS_CALLBACK_URL || "http://localhost:3000/auth/callback",
29
30 // Require email verification (default: false)
31 verifyEmail: false,
32 },
33 },
34 ],
35 },
36 },
37 ],
38 plugins: [
39 // SuperTokens plugin - provides /store/auth/supertokens route for customer creation
40 {
41 resolve: '@patiparnne/medusa-supertokens',
42 options: {},
43 },
44 ],
45});

2. Environment Variables

Add these to your file:

1# SuperTokens Configuration
2SUPERTOKENS_CORE_URL=http://localhost:3567
3SUPERTOKENS_API_DOMAIN=http://localhost:4002
4SUPERTOKENS_API_BASE_PATH=/auth
5SUPERTOKENS_API_KEY=your-api-key
6SUPERTOKENS_CALLBACK_URL=http://localhost:3000/auth/callback

Usage

Authentication Flow

  1. User initiates login: Storefront redirects to hisher-auth login page
  2. User authenticates: Via phone OTP, email/password, or social login (LINE, Google)
  3. Session created: SuperTokens creates a session with access token
  4. Token sent to Medusa: Storefront calls with the token
  5. Profile enriched: Plugin calls on hisher-auth to get user data
  6. Customer created/linked: Medusa creates or retrieves the customer
  7. Medusa JWT returned: Storefront receives Medusa JWT for authenticated requests

API Endpoints

Authenticate with session token:

1POST /auth/customer/supertokens
2Content-Type: application/json
3
4{
5 "access_token": "<supertokens-session-access-token>"
6}

Or via Authorization header:

1POST /auth/customer/supertokens
2Authorization: Bearer <supertokens-session-access-token>

Response (success):

1{
2 "token": "<medusa-jwt-token>"
3}

Legacy Profile Integration

On every authentication, the plugin calls on hisher-auth to:

  • Verify the SuperTokens JWT token
  • Fetch user info and metadata from SuperTokens
  • Return any legacy CRM profile data stored in SuperTokens metadata

This ensures:

  • Real email addresses from legacy CRM are used (instead of generated phone@domain.com)
  • Customer first_name and last_name are populated
  • Legacy member_id is preserved for reference

Options Reference

OptionTypeRequiredDefaultDescription
stringYes-SuperTokens Core URL (e.g., http://localhost:3567)
stringYes-hisher-auth Backend API URL (e.g., http://localhost:4002)
stringNoAPI base path for SuperTokens endpoints
stringNo-SuperTokens Core API key (for direct Core access)
stringNo-Redirect URL after login (storefront callback)
booleanNoRequire email verification before allowing auth

Troubleshooting

"Invalid or expired session token"

  • Ensure SuperTokens Core is running on port 3567
  • Ensure hisher-auth backend is running on port 4002
  • Check that the access token hasn't expired
  • Verify the API key matches (if configured)

"Failed to retrieve user information"

  • The user ID from the session doesn't exist in SuperTokens
  • Check SuperTokens Core logs for errors
  • Check hisher-auth backend logs

Customer created with generated email instead of real email

  • Legacy profile data is fetched during OTP login flow
  • Ensure the user logged in via phone OTP (which fetches legacy profile)
  • Check that returns metadata with email

Connection refused errors

  • Verify is correct and SuperTokens Core is running
  • Verify is correct and hisher-auth backend is running
  • Check network/firewall settings

Related Documentation

  • SuperTokens Documentation
  • Medusa Auth Module

License

MIT

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

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

Passwordless

От Devx Commerce

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

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

Keycloak

От Vymalo

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

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

WebAuthn

От Vymalo

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

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