4.1.4. Protected Routes

In this chapter, you’ll learn how to create protected routes.

What is a Protected Route?#

A protected route is a route that requires requests to be user-authenticated before performing the route's functionality. Otherwise, the request fails, and the user is prevented access.


Default Protected Routes#

Medusa applies an authentication guard on the following routes:

  • Routes starting with /admin require an authenticated admin user.
  • Routes starting with /store/customers/me require an authenticated customer.
Note

Refer to the API Reference for Admin and Store authentication methods.


Authentication Opt-Out#

To disable the authentication guard on custom routes under the /admin or /store/customers/me path prefixes, export an AUTHENTICATE variable in the route file with its value set to false.

For example:

src/api/store/customers/me/custom/route.ts
1import type { MedusaRequest, MedusaResponse } from "@medusajs/medusa"2
3export const GET = async (req: MedusaRequest, res: MedusaResponse) => {4  res.json({5    message: "Hello",6  })7}8
9export const AUTHENTICATE = false

Now, any request sent to the /store/customers/me/custom API route is allowed, regardless if the customer is authenticated.


Access Logged-In Customer#

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 MedusaRequest object.

For example:

src/api/store/customers/me/custom/route.ts
6import { ICustomerModuleService } from "@medusajs/types"7
8export const GET = async (9  req: AuthenticatedMedusaRequest,10  res: MedusaResponse11) => {12  const customerModuleService: ICustomerModuleService = req.scope.resolve(13    ModuleRegistrationName.CUSTOMER14  )15
16  const customer = await customerModuleService.retrieveCustomer(17    req.auth_context.actor_id18  )19
20  // ...21}

In this example, you resolve the Customer Module's main service, then use it to retrieve the logged-in customer, if available.


Access Logged-In Admin User#

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 MedusaRequest object.

For example:

src/api/admin/custom/route.ts
6import { IUserModuleService } from "@medusajs/types"7
8export const GET = async (9  req: AuthenticatedMedusaRequest,10  res: MedusaResponse11) => {12  const userModuleService: IUserModuleService = req.scope.resolve(13    ModuleRegistrationName.USER14  )15
16  const user = await userModuleService.retrieveUser(17    req.auth_context.actor_id18  )19
20  // ...21}

In the route handler, you resolve the User Module's main service, then use it to retrieve the logged-in admin user.


Protect Custom API Routes#

To protect custom API Routes that don’t start with /store/customers/me or /admin, use the authenticate middleware imported from @medusajs/medusa.

For example:

src/api/middlewares.ts
1import { MiddlewaresConfig, authenticate } from "@medusajs/medusa"2
3export const config: MiddlewaresConfig = {4  routes: [5    {6      matcher: "/custom/admin*",7      middlewares: [authenticate("user", ["session", "bearer", "api-key"])],8    },9    {10      matcher: "/custom/customer*",11      middlewares: [authenticate("customer", ["session", "bearer"])],12    },13  ],14}

The authenticate middleware function accepts three parameters:

  1. The type of user authenticating. Use user for authenticating admin users, and customer for authenticating customers.
  2. An array of the types of authentication methods allowed. Both user and customer scopes support session and bearer. The admin scope also supports the api-key authentication method.
  3. An optional object of configurations accepting the following property:
    • 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.
Was this chapter helpful?