Medusa v2 Security
Before writing code
Fetch live docs:
- Web-search
site:docs.medusajs.com authentication for auth strategies and API key setup
- Web-search
site:docs.medusajs.com api key publishable secret for API key types
- Web-search
site:docs.medusajs.com CORS configuration for cross-origin resource sharing
- Fetch
https://docs.medusajs.com/learn/fundamentals/api-routes/middlewares for middleware and auth config
- Web-search
site:docs.medusajs.com medusa-config auth providers for auth provider registration
Authentication Architecture
Admin vs Store Authentication
Medusa v2 separates admin and storefront authentication into distinct flows:
| Aspect |
Admin Auth |
Store Auth |
| Actor type |
user |
customer |
| API scope |
/admin/* routes |
/store/* routes |
| Default provider |
emailpass |
emailpass |
| Session cookie |
Admin session cookie |
Store session cookie |
| API key support |
Secret API key (Bearer) |
Publishable API key (header) |
| JWT usage |
Admin JWT token |
Customer JWT token |
| Middleware |
authenticate("user", ...) |
authenticate("customer", ...) |
Auth Provider System
Auth Module
├── emailpass — email + password (default)
├── google — OAuth 2.0 via Google
├── github — OAuth 2.0 via GitHub
└── custom — implement AbstractAuthModuleProvider
Auth providers are registered in medusa-config.ts under the auth module configuration. Each provider handles a specific identity verification strategy.
API Key Types
| Key Type |
Header |
Purpose |
Visibility |
| Publishable |
x-publishable-api-key |
Storefront API access, scopes to sales channels |
Safe for client-side |
| Secret |
Authorization: Bearer <key> |
Admin API access, full permissions |
Server-side only |
- Publishable keys are created in the admin dashboard and tied to sales channels
- Secret keys grant admin-level access and must never be exposed to browsers
- Store API routes require a publishable key header for sales channel scoping
CORS Configuration
Configure CORS in medusa-config.ts under projectConfig:
| Setting |
Purpose |
Example |
storeCors |
Allowed origins for Store API |
http://localhost:8000 |
adminCors |
Allowed origins for Admin API |
http://localhost:9000 |
authCors |
Allowed origins for Auth routes |
http://localhost:8000,http://localhost:9000 |
- Use comma-separated strings or regex patterns for multiple origins
- In production, restrict to exact domains — never use
* wildcard
authCors must include both storefront and admin origins
JWT and Cookie Secrets
Secret Configuration
| Secret |
Environment Variable |
Purpose |
| Cookie secret |
COOKIE_SECRET |
Signs session cookies |
| JWT secret |
JWT_SECRET |
Signs JSON Web Tokens |
| Admin JWT |
Configured per auth provider |
Admin token signing |
| Store JWT |
Configured per auth provider |
Customer token signing |
- Both
COOKIE_SECRET and JWT_SECRET must be set in production
- Use cryptographically random strings (minimum 32 characters)
- Rotate secrets by updating env vars and restarting the server
Session Management
Sessions are managed via HTTP-only cookies with configurable options:
- Session store — in-memory by default; use Redis for production
- Cookie flags —
httpOnly, secure, sameSite, maxAge
- Session TTL — configurable expiration; defaults vary by auth scope
- Redis session store ensures sessions survive server restarts and work across multiple instances
API Route Authentication
Middleware Configuration
Apply auth middleware in src/api/middlewares.ts:
// Fetch live docs for authenticate() middleware
// signature and actor type options
import { authenticate } from "@medusajs/medusa"
| Middleware Function |
Actor Type |
Use Case |
authenticate("user", ...) |
Admin user |
Admin-only routes |
authenticate("customer", ...) |
Customer |
Store auth-required routes |
authenticate("user", ["bearer","session"]) |
Admin |
Multiple auth strategies |
Auth Scopes on Custom Routes
- Admin routes: place in
src/api/admin/ — auto-protected
- Store routes: place in
src/api/store/ — require publishable key
- Custom routes: manually apply
authenticate() middleware
Auth Provider Implementation
Custom auth providers extend AbstractAuthModuleProvider:
// Fetch live docs for AbstractAuthModuleProvider
// methods: authenticate, register, validateCallback
| Method |
Purpose |
authenticate() |
Verify identity (login) |
register() |
Create new identity |
validateCallback() |
Handle OAuth redirect callbacks |
Security Hardening Checklist
Environment Variables
- Set unique
COOKIE_SECRET and JWT_SECRET (never use defaults)
- Use
DATABASE_URL with SSL mode for PostgreSQL connections
- Store secrets in environment variables, never in source code
Network and Transport
- Enforce HTTPS in production for all API communication
- Restrict CORS origins to exact production domains
- Use
secure: true and sameSite: "strict" on cookies in production
API Keys and Access
- Create separate publishable keys per sales channel
- Rotate secret API keys on a regular schedule
- Audit admin user accounts and remove unused access
- Use the principle of least privilege for API key scoping
Session and Token Security
- Use Redis as session store in production (not in-memory)
- Set appropriate session TTL values (short for admin, configurable for store)
- Implement token refresh logic in storefronts
Best Practices
- Auth provider selection — use
emailpass for standard flows; add OAuth providers for social login; register providers in medusa-config.ts under the auth module
- Key management — publishable keys are public and safe for client bundles; secret keys must only live on the server; never log or commit API keys
- CORS discipline — always set
storeCors, adminCors, and authCors explicitly; test CORS headers before deploying; avoid wildcard origins in production
- Cookie security — enable
httpOnly, secure, and sameSite flags; use Redis-backed sessions for multi-instance deployments; set reasonable TTLs
Fetch the Medusa authentication and security documentation for exact provider registration syntax, middleware options, and cookie configuration before implementing.
1---2name: medusa-security3description: Secure Medusa v2 applications — authentication strategies, API key types (publishable vs secret), CORS configuration, JWT and cookie secrets, admin vs store auth, and session management. Use when configuring security.4allowed-tools: Read, Write, Edit, Bash, Grep, Glob, WebSearch, WebFetch5metadata:6 source: https://skillmd.com/skills/orcaqubits/medusa-security7---89# Medusa v2 Security1011## Before writing code1213**Fetch live docs**:141. Web-search `site:docs.medusajs.com authentication` for auth strategies and API key setup152. Web-search `site:docs.medusajs.com api key publishable secret` for API key types163. Web-search `site:docs.medusajs.com CORS configuration` for cross-origin resource sharing174. Fetch `https://docs.medusajs.com/learn/fundamentals/api-routes/middlewares` for middleware and auth config185. Web-search `site:docs.medusajs.com medusa-config auth providers` for auth provider registration1920## Authentication Architecture2122### Admin vs Store Authentication2324Medusa v2 separates admin and storefront authentication into distinct flows:2526| Aspect | Admin Auth | Store Auth |27|--------|-----------|------------|28| **Actor type** | `user` | `customer` |29| **API scope** | `/admin/*` routes | `/store/*` routes |30| **Default provider** | `emailpass` | `emailpass` |31| **Session cookie** | Admin session cookie | Store session cookie |32| **API key support** | Secret API key (Bearer) | Publishable API key (header) |33| **JWT usage** | Admin JWT token | Customer JWT token |34| **Middleware** | `authenticate("user", ...)` | `authenticate("customer", ...)` |3536### Auth Provider System3738```39Auth Module40├── emailpass — email + password (default)41├── google — OAuth 2.0 via Google42├── github — OAuth 2.0 via GitHub43└── custom — implement AbstractAuthModuleProvider44```4546Auth providers are registered in `medusa-config.ts` under the `auth` module configuration. Each provider handles a specific identity verification strategy.4748## API Key Types4950| Key Type | Header | Purpose | Visibility |51|----------|--------|---------|------------|52| **Publishable** | `x-publishable-api-key` | Storefront API access, scopes to sales channels | Safe for client-side |53| **Secret** | `Authorization: Bearer <key>` | Admin API access, full permissions | Server-side only |5455- Publishable keys are created in the admin dashboard and tied to sales channels56- Secret keys grant admin-level access and must never be exposed to browsers57- Store API routes require a publishable key header for sales channel scoping5859## CORS Configuration6061Configure CORS in `medusa-config.ts` under `projectConfig`:6263| Setting | Purpose | Example |64|---------|---------|---------|65| `storeCors` | Allowed origins for Store API | `http://localhost:8000` |66| `adminCors` | Allowed origins for Admin API | `http://localhost:9000` |67| `authCors` | Allowed origins for Auth routes | `http://localhost:8000,http://localhost:9000` |6869- Use comma-separated strings or regex patterns for multiple origins70- In production, restrict to exact domains — never use `*` wildcard71- `authCors` must include both storefront and admin origins7273## JWT and Cookie Secrets7475### Secret Configuration7677| Secret | Environment Variable | Purpose |78|--------|---------------------|---------|79| **Cookie secret** | `COOKIE_SECRET` | Signs session cookies |80| **JWT secret** | `JWT_SECRET` | Signs JSON Web Tokens |81| **Admin JWT** | Configured per auth provider | Admin token signing |82| **Store JWT** | Configured per auth provider | Customer token signing |8384- Both `COOKIE_SECRET` and `JWT_SECRET` must be set in production85- Use cryptographically random strings (minimum 32 characters)86- Rotate secrets by updating env vars and restarting the server8788## Session Management8990Sessions are managed via HTTP-only cookies with configurable options:9192- **Session store** — in-memory by default; use Redis for production93- **Cookie flags** — `httpOnly`, `secure`, `sameSite`, `maxAge`94- **Session TTL** — configurable expiration; defaults vary by auth scope95- Redis session store ensures sessions survive server restarts and work across multiple instances9697## API Route Authentication9899### Middleware Configuration100101Apply auth middleware in `src/api/middlewares.ts`:102103```ts104// Fetch live docs for authenticate() middleware105// signature and actor type options106import { authenticate } from "@medusajs/medusa"107```108109| Middleware Function | Actor Type | Use Case |110|-------------------|-----------|----------|111| `authenticate("user", ...)` | Admin user | Admin-only routes |112| `authenticate("customer", ...)` | Customer | Store auth-required routes |113| `authenticate("user", ["bearer","session"])` | Admin | Multiple auth strategies |114115### Auth Scopes on Custom Routes116117- Admin routes: place in `src/api/admin/` — auto-protected118- Store routes: place in `src/api/store/` — require publishable key119- Custom routes: manually apply `authenticate()` middleware120121## Auth Provider Implementation122123Custom auth providers extend `AbstractAuthModuleProvider`:124125```ts126// Fetch live docs for AbstractAuthModuleProvider127// methods: authenticate, register, validateCallback128```129130| Method | Purpose |131|--------|---------|132| `authenticate()` | Verify identity (login) |133| `register()` | Create new identity |134| `validateCallback()` | Handle OAuth redirect callbacks |135136## Security Hardening Checklist137138### Environment Variables139140- Set unique `COOKIE_SECRET` and `JWT_SECRET` (never use defaults)141- Use `DATABASE_URL` with SSL mode for PostgreSQL connections142- Store secrets in environment variables, never in source code143144### Network and Transport145146- Enforce HTTPS in production for all API communication147- Restrict CORS origins to exact production domains148- Use `secure: true` and `sameSite: "strict"` on cookies in production149150### API Keys and Access151152- Create separate publishable keys per sales channel153- Rotate secret API keys on a regular schedule154- Audit admin user accounts and remove unused access155- Use the principle of least privilege for API key scoping156157### Session and Token Security158159- Use Redis as session store in production (not in-memory)160- Set appropriate session TTL values (short for admin, configurable for store)161- Implement token refresh logic in storefronts162163## Best Practices164165- **Auth provider selection** — use `emailpass` for standard flows; add OAuth providers for social login; register providers in `medusa-config.ts` under the auth module166- **Key management** — publishable keys are public and safe for client bundles; secret keys must only live on the server; never log or commit API keys167- **CORS discipline** — always set `storeCors`, `adminCors`, and `authCors` explicitly; test CORS headers before deploying; avoid wildcard origins in production168- **Cookie security** — enable `httpOnly`, `secure`, and `sameSite` flags; use Redis-backed sessions for multi-instance deployments; set reasonable TTLs169170Fetch the Medusa authentication and security documentation for exact provider registration syntax, middleware options, and cookie configuration before implementing.