How to Create Custom Endpoints in Medusa

May 26, 2022 by

Shahed  avatar

Shahed Nasser

Shahed  avatar

Shahed Nasser

In this tutorial, you’ll learn how to create custom endpoints on your Medusa server for both the storefront and admin.

How to Create Custom Endpoints in Medusa - Featured image

Notice Medusa is under active development, so the content of this post may be outdated. Please check out our documentation instead.

Medusa is an open source headless commerce platform built using Node.js. It aims to provide developers with a great experience and limitless customization capabilities.

The core of Medusa is the headless server. It exposes a set of APIs that the other 2 components, admin and storefront, can use to connect to the server and access or manipulate data.

In this tutorial, you’ll learn how to create custom endpoints on your Medusa server for both the storefront and admin.

Prerequisites

This tutorial assumes you already have a Medusa server installed. If not, you can follow the Quickstart guide to get started in a few minutes.

Overview

Custom endpoints reside under the Copy to clipboardsrc/api directory in your Medusa Backend. To define a new endpoint, you can add the file Copy to clipboardindex.js under the Copy to clipboardsrc/api directory. This file should export a function that returns an Express router.

Your endpoint can be under any path you wish.

Storefront Endpoint

By Medusa’s conventions, all Storefront REST APIs are prefixed by Copy to clipboard/store. For example, the Copy to clipboard/store/products lets you retrieve the products to display them on your storefront.

Admin Endpoint

By Medusa’s conventions, all Admin REST APIs are prefixed by Copy to clipboard/admin. For example, the Copy to clipboard/admin/products lets you retrieve the products to display them on your Admin.

Implementation

To create a new endpoint, start by creating a new file in Copy to clipboardsrc/api called Copy to clipboardindex.js. At its basic format, Copy to clipboardindex.js should look something like this:

import { Router } from "express"
export default () => {
const router = Router()
router.get("/hello", (req, res) => {
res.json({
message: "Welcome to Your Store!",
})
})
return router
}

This endpoint is accessible under the path Copy to clipboard/hello. If you want to create an endpoint for the storefront and follow Medusa’s conventions you can prefix the path with Copy to clipboard/store:

router.get("/store/hello", (req, res) => {

Similarly, you can create an endpoint for the admin and follow Medusa’s conventions by prefixing the path with Copy to clipboard/admin:

router.get("/admin/hello", (req, res) => {

Making Endpoints Accessible from the Admin

If you’re customizing the admin dashboard or creating your own, you need to use the Copy to clipboardcors library. An Copy to clipboardOPTIONS request should be added for each route and handle the requests with the Copy to clipboardcors library.

First, you need to import your Medusa’s configurations along with the Copy to clipboardcors library:

import cors from "cors"
import { projectConfig } from "../../medusa-config"

Then, create an object that holds the CORS configurations:

const corsOptions = {
origin: projectConfig.admin_cors.split(","),
credentials: true,
}

Finally, for each route you add, create an Copy to clipboardOPTIONS request:

router.options("/admin/hello", cors(corsOptions))
router.get("/admin/hello", (req, res) => {
//...
})

Multiple Endpoints

Same File

You can add more than one endpoints in Copy to clipboardsrc/api/index.js:

router.get("/admin/hello", (req, res) => {
res.json({
message: "Welcome to Your Store!",
})
})
router.get("/admin/bye", (req, res) => {
res.json({
message: "Come back again!",
})
})

Multiple Files

Alternatively, you can add multiple files for each endpoint or set of endpoints for readability and easy maintenance.

To do that with the previous example, first, create the file Copy to clipboardsrc/api/hello.js with the following content:

export default (router) => {
router.get("/admin/hello", (req, res) => {
res.json({
message: "Welcome to Your Store!",
})
})
}

You export a function that receives an Express router as a parameter and adds the endpoint Copy to clipboardadmin/hello to it.

Next, create the file Copy to clipboardsrc/api/bye.js with the following content:

export default (router) => {
router.get("/admin/bye", (req, res) => {
res.json({
message: "Come back again!",
})
})
}

Again, you export a function that receives an Express router as a parameter and adds the endpoint Copy to clipboardadmin/bye to it.

Finally, in Copy to clipboardsrc/api/index.js import the two functions at the beginning of the file:

import helloRoute from "./hello"
import byeRoute from "./bye"

and in the exported function, call each of the functions passing them the Express router:

export default () => {
const router = Router()
helloRoute(router)
byeRoute(router)
return router
}

Use Services

Services in Medusa bundle a set of functionalities related to a model into one class. Then, you can use that class anywhere in your backend. For example, you can use the Copy to clipboardProductService to retrieve products or perform operations like creating or updating a product.

You can retrieve any registered service in your endpoint using Copy to clipboardreq.scope.resolve passing it the service’s registration name.

Here’s an example of an endpoint that retrieves the count of products in your store:

router.get("/admin/products/count", (req, res) => {
const productService = req.scope.resolve("productService")
productService.count().then((count) => {
res.json({
count,
})
})
})

The Copy to clipboardproductService has a Copy to clipboardcount method that returns a Promise. This Promise resolves to the count of the products. You return a JSON of the product count.

Protected Routes for

Protected routes are routes that should be accessible by logged-in users only.

To make a route protected, first, import the Copy to clipboardauthenticate middleware:

import authenticate from "@medusajs/medusa/dist/api/middlewares/authenticate"

Then, add the middleware to your route:

router.get("/store/products/count", authenticate(), (req, res) => {
//...
})

Now, only authenticated customers or users can access this endpoint.

Accessing Current Customer

You can get the logged-in customer’s ID using Copy to clipboardreq.user:

const id = req.user.customer_id

To get the customer’s details, you can use the Copy to clipboardcustomerService:

const id = req.user.customer_id
const customerService = req.scope.resolve("customerService")
const customer = await customerService.retrieve(id)

Accessing Current User

You can get the logged-in user ID using Copy to clipboardreq.user:

const id = req.user.userId

To get the user’s details, you can use the Copy to clipboarduserService:

const id = req.user.userId
const userService = req.scope.resolve("userService")
const user = await userService.retrieve(id)

Route Parameters

The routes you create receive 2 parameters. The first one is the absolute path to the root directory that your server is running from. The second one is an object that has your plugin's options. If your API route is not implemented in a plugin, then it will be an empty object.

export default (rootDirectory, pluginOptions) => {
const router = Router()
//...
}

What’s Next?

Endpoints are just one essential part of Medusa’s architecture. Here are more resources to learn more about Medusa’s server and how to customize it:

Should you have any issues or questions related to Medusa, then feel free to reach out to the Medusa team via Discord.

Share this post

Try Medusa

Spin up your environment in a few minutes.