Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 33 ยท The APIs

The Admin API and Authentication

Learn how the Medusa Admin API authenticates users with JWTs, cookie sessions and secret API keys, how actor types work, and how to paginate and select fields.

The Store API is for shoppers. The Admin API, under /admin, is for the people and systems that run the shop: it creates products, changes prices, fulfills orders, issues refunds and manages users. That power means every Admin route is protected, and understanding how it is protected is the first step before you build your own routes, integrations or admin extensions.

This lesson covers the three ways to authenticate against the Admin API, how Medusa's Auth Module separates identity from who you act as, the shape of list endpoints, and the JS SDK. Real requests are read-only because they need a running Medusa server. The runnable stand-in issues and verifies signed tokens with node:crypto, so you can see exactly what a JWT is and why tampering fails. The stand-in is not Medusa's code: it demonstrates the mechanism.

Admin users and the Auth Module

An admin user is created from the command line or the Admin invite flow:

Terminal
npx medusa user -e [email protected] -p supersecret

That command creates two records in two different modules, and the split is the key idea:

  • An auth identity in the Auth Module: the ability to prove who you are. It holds one or more provider identities (for example an emailpass entry with a hashed password) and app_metadata that says which application record it belongs to.
  • A user in the User Module: the domain record (email, name, avatar) that the Admin shows.

The glue is app_metadata, which contains an actor type and an actor id, such as user with user_01... or customer with cus_01.... When you authenticate, you ask Medusa to log in as an actor type. The same auth system therefore serves admins and shoppers without mixing them up: a customer token carries actor_type: "customer" and is refused by routes that require user. You can add your own actor types for vendors or partners, which matters for marketplaces.

Three ways to authenticate

1. Bearer JWT. You log in and receive a signed token, then send it on every request:

HTTP
POST /auth/user/emailpass
{ "email": "[email protected]", "password": "supersecret" }

โ†’ { "token": "eyJhbGciOi..." }

GET /admin/products
Authorization: Bearer eyJhbGciOi...

The URL has the shape /auth/{actor_type}/{provider}. The token is a JSON Web Token signed with the server's JWT_SECRET; its payload holds the actor id, the actor type and the auth identity. Medusa verifies the signature and expiry on each request and does not look the token up in a database, which makes it cheap and stateless. It also means a stolen token works until it expires.

2. Cookie session. Browsers should not keep a JWT in localStorage, where any script can read it. The Admin dashboard instead exchanges the token for a session cookie (the session is signed with COOKIE_SECRET, httpOnly, and not readable by scripts):

HTTP
POST /auth/session
Authorization: Bearer eyJhbGciOi...

โ†’ response sets a session cookie
GET /admin/products        (browser sends the cookie automatically)

Because cookies are sent automatically, cookie-based requests also raise the cross-site request question; that is part of the CORS configuration in Security and Performance.

3. Secret API key (API token). For server-to-server scripts there is no human to log in. In the Admin you create a secret API key, and the script sends it with HTTP Basic authentication, using the key as the username and an empty password:

HTTP
GET /admin/products
Authorization: Basic c2tfMDFIWC4uLjo=      (base64 of "sk_01HX...:")

Secret keys are for backends, CI jobs and integrations. Treat them like passwords: keep them in environment variables, never in storefront code, and revoke them in the Admin when they leak. Do not confuse them with the publishable key from The Store API, which is public by design.

flowchart TD
    A["Request to /admin/*"] --> B{"Which credential?"}
    B -->|"Bearer JWT"| C["Verify signature and expiry"]
    B -->|"Session cookie"| D["Load session, read auth context"]
    B -->|"Basic secret key"| E["Look up the API key"]
    C --> F["actor_type must be user"]
    D --> F
    E --> F
    F --> G["Route handler runs"]

Three credentials, one check: the request must end up as an authenticated actor of the right type.

Calling Admin endpoints

Admin resources follow a consistent REST style: GET /admin/products, POST /admin/products, GET /admin/products/:id, POST /admin/products/:id (update), DELETE /admin/products/:id. Medusa uses POST for updates. List endpoints share the same query vocabulary:

HTTP
GET /admin/orders?limit=20&offset=40&order=-created_at&fields=id,display_id,total,*customer
Authorization: Bearer ...
  • limit and offset page through results. The response always contains count (total matches), limit, offset and the items under a named key (orders).
  • order sorts; a leading - means descending.
  • fields selects fields and relations, with the same *relation, +extra and -removed syntax as the Store API. The Admin returns more by default, but selecting fields is still the way to keep responses small.
  • Filters are plain query parameters such as q= for search or created_at[$gte]=..., depending on the resource.

Deep paging with a large offset gets slower because the database skips rows. For exports of everything, loop with a fixed limit and an increasing offset inside a background job, as in Scheduled Jobs.

The Admin JS SDK

The same JS SDK used by storefronts has an admin namespace. In a script you configure it with a token or API key; in the dashboard you configure it with a cookie session (read-only, check names for your version):

TypeScript
import Medusa from "@medusajs/js-sdk"

const sdk = new Medusa({
  baseUrl: "https://shop.example.com",
  auth: { type: "jwt" },
})

await sdk.auth.login("user", "emailpass", {
  email: "[email protected]",
  password: process.env.ADMIN_PASSWORD!,
})

const { products, count } = await sdk.admin.product.list({
  limit: 50,
  fields: "id,title,status",
})
console.log(`${products.length} of ${count}`)

Use auth: { type: "session" } in a browser dashboard so the cookie does the work. For custom admin screens, see Admin Dashboard Extensions.

Stand-in 1: issuing and verifying a signed token

A JWT is three base64url parts: a header, a payload, and a signature that proves nobody changed the first two. This stand-in builds one with HMAC-SHA256 and verifies it the way a server must: recompute the signature, compare in constant time, then check the expiry and the actor type. It is a teaching model of the mechanism, not Medusa's implementation (which uses a maintained JWT library and JWT_SECRET).

Node.js Sign and verify a JWT-style token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The forged token fails because changing one character of the payload changes the signature that the server computes, and the attacker does not know the secret. The customer token is a perfectly valid token that is still refused: authentication (who are you) and authorization (may you do this here) are separate checks, and the actor type is how Medusa performs the second one for built-in routes.

Stand-in 2: three credentials and a paginated list

The second stand-in combines the three credential styles behind one authenticate() function and serves a paginated list with limit, offset, order and count, so you can see the response contract.

Node.js Credentials and the list response contract

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the last call: a valid customer token gets 401 on an admin list. Also check count: it stays 7 on every page while orders shows only the slice, so a client can compute the number of pages as Math.ceil(count / limit).

Common mistakes

  • Putting a secret API key in browser code. Anything in a bundle is public. Use the publishable key there.
  • Storing the admin JWT in localStorage. Prefer a session cookie in browsers.
  • Weak or default JWT_SECRET and COOKIE_SECRET. Anyone who guesses the secret can mint admin tokens. Use long random values, different per environment.
  • Assuming a valid token means permission. Check the actor type (and, for your own routes, ownership) as shown in Custom API Routes and Middleware.
  • Over-fetching on list endpoints. Request only the fields you need.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the actor type in a Medusa token tell the server?

    An auth identity points to an actor through app_metadata. The actor type lets routes accept admins and refuse customers even though both authenticate through the same module.
  2. 2. Why is a JWT cheap to verify on every request?

    The signature proves the payload is unchanged, and the payload carries the claims. The trade-off is that a stolen token stays valid until it expires.
  3. 3. Which credential is right for a nightly script that imports products from your ERP?

    Secret API keys are meant for server-to-server work and can be revoked in the Admin. The publishable key only scopes storefront reads, and a customer token is refused by admin routes.
  4. 4. A list response has count 120, limit 20 and offset 40. Which page is that?

    An offset of 40 skips two pages of 20, so this is the third page, and 120 divided by 20 gives 6 pages in total.

Summary

  • The Auth Module proves identity; the actor type and id connect an identity to a user, customer or custom actor.
  • Admin routes accept a bearer JWT, a session cookie or a secret API key; browsers should prefer cookies and scripts should use secret keys.
  • Tokens are signed, not secret: never trust a payload without verifying its signature, expiry and actor type.
  • List endpoints return the items, count, limit and offset, and accept order and fields.
  • Keep JWT_SECRET, COOKIE_SECRET and secret API keys out of frontend code and out of version control.

Next, learn how the backend itself reads linked data: Query: Fields, Filters and Pagination.