1 import { Table } from "docs-ui"
2
3 export const metadata = {
4 title: `${pageNumber} Protected API Routes`,
5 }
6
7 # {metadata.title}
8
9 In this chapter, you’ll learn how to create protected API routes.
10
11 ## What is a Protected API Route?
12
13 By default, an API route is publicly accessible, meaning that any user can access it without authentication. This is useful for public API routes that allow users to browse products, view collections, and so on.
14
15 A protected API route is an API route that requires requests to be user-authenticated before performing the route's functionality. Otherwise, the request fails, and the user is prevented access.
16
17 Protected API routes are useful for routes that require user authentication, such as creating a product or managing an order. These routes must only be accessed by authenticated admin users.
18
19 <Note title="Tip">
20
21 Refer to the API Reference for [Admin](!api!/admin/authentication) and [Store](!api!/store/authentication) to learn how to send authenticated requests.
22
23 </Note>
24
25 ---
26
27 ## Default Protected Routes
28
29 Any API route, including your custom API routes, are protected if they start with the following prefixes:
30
31 <Table>
32 <Table.Header>
33 <Table.Row>
34 <Table.HeaderCell>
35 Route Prefix
36 </Table.HeaderCell>
37 <Table.HeaderCell>
38 Access
39 </Table.HeaderCell>
40 </Table.Row>
41 </Table.Header>
42 <Table.Body>
43 <Table.Row>
44 <Table.Cell>
45 `/admin`
46 </Table.Cell>
47 <Table.Cell>
48 Only authenticated admin users can access.
49 </Table.Cell>
50 </Table.Row>
51 <Table.Row>
52 <Table.Cell>
53 `/store/customers/me`
54 </Table.Cell>
55 <Table.Cell>
56 Only authenticated customers can access.
57 </Table.Cell>
58 </Table.Row>
59 </Table.Body>
60 </Table>
61
62 Refer to the API Reference for [Admin](!api!/admin/authentication) and [Store](!api!/store/authentication) to learn how to send authenticated requests.
63
64 ### Opt-Out of Default Authentication Requirement
65
66 If you create a custom API route under a prefix that is protected by default, you can opt-out of the authentication requirement by exporting an `AUTHENTICATE` variable in the route file with its value set to `false`.
67
68 For example, to disable authentication requirement for a custom API route created at `/admin/custom`, you can export an `AUTHENTICATE` variable in the route file:
69
70 ```ts title="src/api/admin/custom/route.ts" highlights={[["15"]]}
71 import type {
72 AuthenticatedMedusaRequest,
73 MedusaResponse,
74 } from "@medusajs/framework/http"
75
76 export const GET = async (
77 req: AuthenticatedMedusaRequest,
78 res: MedusaResponse
79 ) => {
80 res.json({
81 message: "Hello",
82 })
83 }
84
85 export const AUTHENTICATE = false
86 ```
87
88 Now, any request sent to the `/admin/custom` API route is allowed, regardless if the admin user is authenticated.
89
90 ---
91
92 ## Protect Custom API Routes
93
94 You can protect API routes using the `authenticate` [middleware](../middlewares/page.mdx) from the Medusa Framework. When applied to a route, the middleware checks that:
95
96 - The correct actor type (for example, `user`, `customer`, or a custom actor type) is authenticated.
97 - The correct authentication method is used (for example, `session`, `bearer`, or `api-key`).
98
99 For example, you can add the `authenticate` middleware in the `src/api/middlewares.ts` file to protect a custom API route:
100
101 export const highlights = [
102 [
103 "10",
104 "authenticate",
105 "Only authenticated admin users can access routes starting with `/custom/admin`",
106 ],
107 [
108 "14",
109 "authenticate",
110 "Only authenticated customers can access routes starting with `/custom/customers`",
111 ],
112 ]
113
114 ```ts title="src/api/middlewares.ts" highlights={highlights}
115 import {
116 defineMiddlewares,
117 authenticate,
118 } from "@medusajs/framework/http"
119
120 export default defineMiddlewares({
121 routes: [
122 {
123 matcher: "/custom/admin*",
124 middlewares: [authenticate("user", ["session", "bearer", "api-key"])],
125 },
126 {
127 matcher: "/custom/customer*",
128 middlewares: [authenticate("customer", ["session", "bearer"])],
129 },
130 ],
131 })
132 ```
133
134 The `authenticate` middleware function accepts three parameters:
135
136 1. The type of user authenticating. Use `user` for authenticating admin users, and `customer` for authenticating customers. You can also pass `*` to allow all types of users, or pass an array of actor types.
137 2. An array of types of authentication methods allowed. Both `user` and `customer` scopes support `session` and `bearer`. The `admin` scope also supports the `api-key` authentication method.
138 3. An optional object of configurations accepting the following properties:
139 - `allowUnauthenticated`: (default: `false`) A boolean indicating whether authentication is required. For example, you may have an API route where you want to access the logged-in customer if available, but guest customers can still access it too. Learn more about how the middleware handles invalid credentials in the [next section](#invalid-credentials-in-unauthenticated-routes).
140 - `allowUnregistered` (default: `false`): A boolean indicating whether users can access this route with a registration token, instead of an authentication token. This is useful if you have a custom actor type, such as `manager`, and you're creating an API route that allows these users to register themselves. Learn more in the [Custom Actor-Type Guide](!resources!/commerce-modules/auth/create-actor-type).
141 - `requireMfa` (default: `true` for authenticated routes, since [Medusa v2.20.0](https://github.com/medusajs/medusa/releases/tag/v2.20.0)): A boolean or an object `{ maxAgeSeconds: number }` indicating whether a completed MFA challenge is required to access this route. When set to `true`, any request from an identity with MFA enabled must have completed an MFA challenge. When set to `{ maxAgeSeconds: number }`, the challenge must also have been completed within the specified number of seconds. Set to `false` to allow access regardless of MFA status (for example, on the MFA challenge verification route itself). Learn more in the [Multi-Factor Authentication guide](!resources!/commerce-modules/auth/mfa).
142
143 ### Example: Custom Actor Type
144
145 For example, to require authentication of a custom actor type `manager` to an API route:
146
147 ```ts title="src/api/middlewares.ts"
148 import {
149 defineMiddlewares,
150 authenticate,
151 } from "@medusajs/framework/http"
152
153 export default defineMiddlewares({
154 routes: [
155 {
156 matcher: "/manager*",
157 middlewares: [authenticate("manager", ["session", "bearer"])],
158 },
159 ],
160 })
161 ```
162
163 <Note title="Tip">
164
165 Refer to the [Custom Actor-Type Guide](!resources!/commerce-modules/auth/create-actor-type) for detailed explanation on how to create a custom actor type and apply authentication middlewares.
166
167 </Note>
168
169 ### Example: Allow Multiple Actor Types
170
171 To allow multiple actor types to access an API route, pass an array of actor types to the `authenticate` middleware:
172
173 ```ts title="src/api/middlewares.ts"
174 import {
175 defineMiddlewares,
176 authenticate,
177 } from "@medusajs/framework/http"
178
179 export default defineMiddlewares({
180 routes: [
181 {
182 matcher: "/custom*",
183 middlewares: [authenticate(["user", "customer"], ["session", "bearer"])],
184 },
185 ],
186 })
187 ```
188
189 ### Invalid Credentials in Unauthenticated Routes
190
191 When you set `allowUnauthenticated` to `true`, the `authenticate` middleware never rejects a request. It verifies the credentials of the request, if any, then passes the request to the next handler in both of the following cases:
192
193 - The request carries no credentials at all.
194 - The request carries credentials that fail verification, such as an expired or a tampered JWT token.
195
196 In both cases, the middleware doesn't set the `auth_context` property of the request object. This is the intended behavior: the middleware's only job is to attach an authenticated actor when it can verify one, and the route decides what to do when it can't.
197
198 <Note title="Warning" type="warning">
199
200 Because both cases look the same to your route handler, don't treat a missing `auth_context` as proof that the request presented no credentials. If your route's logic differs between a signed-out request and an expired session, add the check explained next.
201
202 </Note>
203
204 #### Reject Invalid Credentials
205
206 To answer with a `401` error when a request presents credentials that fail verification, while still allowing requests that present no credentials, add a middleware that runs after the `authenticate` middleware.
207
208 Create the file `src/api/middlewares/reject-invalid-auth.ts` with the following content:
209
210 export const rejectInvalidAuthHighlights = [
211 ["15", "authorization", "Check whether the request sent a bearer token."],
212 ["19", "session", "Check whether the request sent a session cookie holding an authentication context."],
213 ["21", "auth_context", "The `authenticate` middleware didn't verify the presented credentials."],
214 ]
215
216 ```ts title="src/api/middlewares/reject-invalid-auth.ts" highlights={rejectInvalidAuthHighlights}
217 import {
218 AuthenticatedMedusaRequest,
219 MedusaNextFunction,
220 MedusaResponse,
221 } from "@medusajs/framework/http"
222 import {
223 MedusaError,
224 } from "@medusajs/framework/utils"
225
226 export async function rejectInvalidAuth(
227 req: AuthenticatedMedusaRequest,
228 res: MedusaResponse,
229 next: MedusaNextFunction
230 ) {
231 const authHeader = req.headers.authorization ?? ""
232 const hasToken = authHeader
233 .toLowerCase()
234 .startsWith("bearer ")
235 const hasSession = Boolean(req.session?.auth_context)
236
237 if ((hasToken || hasSession) && !req.auth_context) {
238 return next(
239 new MedusaError(
240 MedusaError.Types.UNAUTHORIZED,
241 "Your session is invalid or has expired."
242 )
243 )
244 }
245
246 next()
247 }
248 ```
249
250 The middleware considers a request as presenting credentials if it has an `Authorization` header with a bearer token, or a session cookie holding an authentication context. If the request presents credentials but the `authenticate` middleware didn't set `auth_context`, the middleware rejects the request with a `401` error.
251
252 Then, apply the middleware after the `authenticate` middleware:
253
254 ```ts title="src/api/middlewares.ts" highlights={[["17", "rejectInvalidAuth", "Run the check after authentication."]]}
255 import {
256 defineMiddlewares,
257 authenticate,
258 } from "@medusajs/framework/http"
259 import {
260 rejectInvalidAuth,
261 } from "./middlewares/reject-invalid-auth"
262
263 export default defineMiddlewares({
264 routes: [
265 {
266 matcher: "/custom/public*",
267 middlewares: [
268 authenticate("customer", ["session", "bearer"], {
269 allowUnauthenticated: true,
270 }),
271 rejectInvalidAuth,
272 ],
273 },
274 ],
275 })
276 ```
277
278 The order of the middlewares matters, since `rejectInvalidAuth` reads the `auth_context` that the `authenticate` middleware sets.
279
280 Now, a request with no credentials reaches the route as a guest, a request with valid credentials reaches the route with its `auth_context` set, and a request with expired or invalid credentials receives a `401` error. A storefront can then prompt the customer to log in again instead of showing them the guest experience.
281
282 ### Override Authentication for Medusa's API Routes
283
284 In some cases, you may want to override the authentication requirement for Medusa's API routes. For example, you may want to allow custom actor types to access existing protected API routes.
285
286 It's not possible to change the [authentication middleware](../middlewares/page.mdx) applied to an existing API route. Instead, you need to replicate the API route and apply the authentication middleware to it.
287
288 Learn more in the [Override API Routes](../override/page.mdx) chapter.
289
290 ---
291
292 ## Access Authentication Details in API Routes
293
294 To access the authentication details in an API route, such as the logged-in user's ID, set the type of the first request parameter to `AuthenticatedMedusaRequest`. It extends `MedusaRequest`:
295
296 ```ts highlights={[["7", "AuthenticatedMedusaRequest"]]}
297 import type {
298 AuthenticatedMedusaRequest,
299 MedusaResponse,
300 } from "@medusajs/framework/http"
301
302 export const GET = async (
303 req: AuthenticatedMedusaRequest,
304 res: MedusaResponse
305 ) => {
306 // ...
307 }
308 ```
309
310 The `auth_context.actor_id` property of `AuthenticatedMedusaRequest` holds the ID of the authenticated user or customer. If there isn't any authenticated user or customer, `auth_context` is `undefined`.
311
312 For example:
313
314 ```ts title="src/api/store/custom/route.ts" highlights={[["10", "actor_id"]]}
315 import type {
316 AuthenticatedMedusaRequest,
317 MedusaResponse,
318 } from "@medusajs/framework/http"
319
320 export const GET = async (
321 req: AuthenticatedMedusaRequest,
322 res: MedusaResponse
323 ) => {
324 const id = req.auth_context?.actor_id
325
326 // ...
327 }
328 ```
329
330 In this example, you retrieve the ID of the authenticated user, customer, or custom actor type from the `auth_context` property of the `AuthenticatedMedusaRequest` object.
331
332 <Note>
333
334 If you opt-out of authentication in a route as mentioned in the [Opt-Out section](#opt-out-of-default-authentication-requirement), you can't access the authenticated user or customer anymore. Use the [authenticate middleware](#protect-custom-api-routes) instead to protect the route.
335
336 </Note>
337
338 ### Retrieve Logged-In Customer's Details
339
340 You can access the logged-in customer’s ID in all API routes starting with `/store` using the `auth_context.actor_id` property of the `AuthenticatedMedusaRequest` object. You can then use [Query](../../query/page.mdx) to retrieve the customer details, or pass the ID to a [workflow](../../workflows/page.mdx) that performs business logic.
341
342 For example:
343
344 export const customerHighlights = [
345 ["13", "customerId", "Retrieve the logged-in customer's ID."],
346 ["18", "query", "Retrieve the customer details."],
347 ["25", "throwIfKeyNotFound", "Throw an error if the customer with\nthe specified ID is not found."],
348 ]
349
350 ```ts title="src/api/store/custom/route.ts" highlights={customerHighlights}
351 import type {
352 AuthenticatedMedusaRequest,
353 MedusaResponse,
354 } from "@medusajs/framework/http"
355 import {
356 ContainerRegistrationKeys,
357 } from "@medusajs/framework/utils"
358
359 export const GET = async (
360 req: AuthenticatedMedusaRequest,
361 res: MedusaResponse
362 ) => {
363 const customerId = req.auth_context?.actor_id
364 const query = req.scope.resolve(
365 ContainerRegistrationKeys.QUERY
366 )
367
368 const { data: [customer] } = await query.graph({
369 entity: "customer",
370 fields: ["*"],
371 filters: {
372 id: customerId,
373 },
374 }, {
375 throwIfKeyNotFound: true,
376 })
377
378 // do something with the customer data...
379 }
380 ```
381
382 In this example, you retrieve the customer's ID and resolve Query from the [Medusa container](../../medusa-container/page.mdx).
383
384 Then, you use Query to retrieve the customer details. The `throwIfKeyNotFound` option throws an error if the customer with the specified ID is not found.
385
386 After that, you can use the customer's details in your API route.
387
388 ### Retrieve Logged-In Admin User's Details
389
390 You can access the logged-in admin user’s ID in all API routes starting with `/admin` using the `auth_context.actor_id` property of the `AuthenticatedMedusaRequest` object. You can then use [Query](../../query/page.mdx) to retrieve the user details, or pass the ID to a [workflow](../../workflows/page.mdx) that performs business logic.
391
392 For example:
393
394 export const adminHighlights = [
395 ["13", "userId", "Retrieve the logged-in admin user's ID."],
396 ["18", "query", "Retrieve the user details."],
397 ["25", "throwIfKeyNotFound", "Throw an error if the user with\nthe specified ID is not found."],
398 ]
399
400 ```ts title="src/api/admin/custom/route.ts" highlights={adminHighlights}
401 import type {
402 AuthenticatedMedusaRequest,
403 MedusaResponse,
404 } from "@medusajs/framework/http"
405 import {
406 ContainerRegistrationKeys,
407 } from "@medusajs/framework/utils"
408
409 export const GET = async (
410 req: AuthenticatedMedusaRequest,
411 res: MedusaResponse
412 ) => {
413 const userId = req.auth_context?.actor_id
414 const query = req.scope.resolve(
415 ContainerRegistrationKeys.QUERY
416 )
417
418 const { data: [user] } = await query.graph({
419 entity: "user",
420 fields: ["*"],
421 filters: {
422 id: userId,
423 },
424 }, {
425 throwIfKeyNotFound: true,
426 })
427
428 // do something with the user data...
429 }
430 ```
431
432 In this example, you retrieve the admin user's ID and resolve Query from the [Medusa container](../../medusa-container/page.mdx).
433
434 Then, you use Query to retrieve the user details. The `throwIfKeyNotFound` option throws an error if the user with the specified ID is not found.
435
436 After that, you can use the user's details in your API route.