Skip to main content

Example: How to Create Onboarding Widget

In this guide, you’ll learn how to build the onboarding widget available in the admin dashboard the first time you install a Medusa project.

The onboarding widget is already implemented within the codebase of your Medusa backend. This guide is helpful if you want to understand how it was implemented or you want an example of customizing the Medusa admin and backend.

What you’ll be Building

By following this tutorial, you’ll:

  • Build an onboarding flow in the admin that takes the user through creating a sample product and order. This flow has four steps and navigates the user between four pages in the admin before completing the guide. This will be implemented using Admin Widgets.
  • Keep track of the current step the user has reached by creating a table in the database and an API endpoint that the admin widget uses to retrieve and update the current step. These customizations will be applied to the backend.

Onboarding Widget Demo


Prerequisites

Before you follow along this tutorial, you must have a Medusa backend installed. If not, you can use the following command to get started:

npx create-medusa-app@latest

Please refer to the create-medusa-app documentation for more details on this command, including prerequisites and troubleshooting.


Preparation Steps

The steps in this section are used to prepare for the custom functionalities you’ll be creating in this tutorial.

(Optional) TypeScript Configurations and package.json

If you're using TypeScript in your project, it's highly recommended to setup your TypeScript configurations and package.json as mentioned in this guide.

Install Medusa React

Medusa React is a React library that facilitates using Medusa’s endpoints within your React application. It also provides the utility to register and use custom endpoints.

To install Medusa React and its required dependencies, run the following command in the root directory of the Medusa backend:

npm install medusa-react @tanstack/react-query

Implement Helper Resources

The resources in this section are used for typing, layout, and design purposes, and they’re used in other essential components in this tutorial.

Each of the collapsible elements below hold the path to the file that you should create, and the content of that file.


Step 1: Customize Medusa Backend

If you’re not interested in learning about backend customizations, you can skip to step 2.

In this step, you’ll customize the Medusa backend to:

  1. Add a new table in the database that stores the current onboarding step. This requires creating a new entity, repository, and migration.
  2. Add a new endpoint that allows to retrieve and update the current onboarding step. This requires creating a new service and endpoint.

Create Entity

An entity represents a table in the database. It’s based on Typeorm, so it requires creating a repository and a migration to be used in the backend.

To create the entity, create the file src/models/onboarding.ts with the following content:

src/models/onboarding.ts
import { BaseEntity } from "@medusajs/medusa"
import { Column, Entity } from "typeorm"

@Entity()
export class OnboardingState extends BaseEntity {
@Column()
current_step: string

@Column()
is_complete: boolean

@Column()
product_id: string
}

Then, create the file src/repositories/onboarding.ts that holds the repository of the entity with the following content:

src/repositories/onboarding.ts
import {
dataSource,
} from "@medusajs/medusa/dist/loaders/database"
import { OnboardingState } from "../models/onboarding"

const OnboardingRepository = dataSource.getRepository(
OnboardingState
)

export default OnboardingRepository

You can learn more about entities and repositories in this documentation.

Create Migration

A migration is used to reflect database changes in your database schema.

To create a migration, run the following command in the root of your Medusa backend:

npx typeorm migration:create src/migrations/CreateOnboarding

This will create a file in the src/migrations directory with the name formatted as <TIMESTAMP>-CreateOnboarding.ts.

In that file, import the generateEntityId utility method at the top of the file:

import { generateEntityId } from "@medusajs/utils"

Then, replace the up and down methods in the migration class with the following content:

export class CreateOnboarding1685715079776 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "onboarding_state" ("id" character varying NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "current_step" character varying NULL, "is_complete" boolean, "product_id" character varying NULL)`
)

await queryRunner.query(
`INSERT INTO "onboarding_state" ("id", "current_step", "is_complete") VALUES ('${generateEntityId(
"",
"onboarding"
)}' , NULL, false)`
)
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TABLE "onboarding_state"`)
}
}

Don’t copy the name of the class in the code snippet above. Keep the name you have in the file.

Finally, to reflect the migration in the database, run the build and migration commands:

npm run build
npx medusa migrations run

You can learn more about migrations in this guide.

Create Service

A service is a class that holds helper methods related to an entity. For example, methods to create or retrieve a record of that entity. Services are used by other resources, such as endpoints, to perform functionalities related to an entity.

So, before you add the endpoints that allow retrieving and updating the onboarding state, you need to add the service that implements these helper functionalities.

Start by creating the file src/types/onboarding.ts with the following content:

src/types/onboarding.ts
import { OnboardingState } from "../models/onboarding"

export type UpdateOnboardingStateInput = {
current_step?: string;
is_complete?: boolean;
product_id?: string;
};

export interface AdminOnboardingUpdateStateReq {}

export type OnboardingStateRes = {
status: OnboardingState;
};

This file holds the necessary types that will be used within the service you’ll create, and later in your onboarding flow widget.

Then, create the file src/services/onboarding.ts with the following content:

src/services/onboarding.ts
import { TransactionBaseService } from "@medusajs/medusa"
import OnboardingRepository from "../repositories/onboarding"
import { OnboardingState } from "../models/onboarding"
import { EntityManager, IsNull, Not } from "typeorm"
import { UpdateOnboardingStateInput } from "../types/onboarding"

type InjectedDependencies = {
manager: EntityManager;
onboardingRepository: typeof OnboardingRepository;
};

class OnboardingService extends TransactionBaseService {
protected onboardingRepository_: typeof OnboardingRepository

constructor({ onboardingRepository }: InjectedDependencies) {
super(arguments[0])

this.onboardingRepository_ = onboardingRepository
}

async retrieve(): Promise<OnboardingState | undefined> {
const onboardingRepo = this.activeManager_.withRepository(
this.onboardingRepository_
)

const status = await onboardingRepo.findOne({
where: { id: Not(IsNull()) },
})

return status
}

async update(
data: UpdateOnboardingStateInput
): Promise<OnboardingState> {
return await this.atomicPhase_(
async (transactionManager: EntityManager) => {
const onboardingRepository =
transactionManager.withRepository(
this.onboardingRepository_
)

const status = await this.retrieve()

for (const [key, value] of Object.entries(data)) {
status[key] = value
}

return await onboardingRepository.save(status)
}
)
}
}

export default OnboardingService

This service class implements two methods retrieve to retrieve the current onboarding state, and update to update the current onboarding state.

You can learn more about services in this documentation.

Create Endpoint

The last part of this step is to create the endpoints that you’ll consume in the admin widget. There will be two endpoints: Get Onboarding State and Update Onboarding State.

To add the Get Onboarding State endpoint, create the file src/api/routes/admin/onboarding/get-status.ts with the following content:

src/api/routes/admin/onboarding/get-status.ts
import { Request, Response } from "express"
import OnboardingService from "../../../../services/onboarding"

export default async function getOnboardingStatus(
req: Request,
res: Response
) {
const onboardingService: OnboardingService =
req.scope.resolve("onboardingService")

const status = await onboardingService.retrieve()

res.status(200).json({ status })
}

Notice how this endpoint uses the OnboardingService's retrieve method to retrieve the current onboarding state. It resolves the OnboardingService using the Dependency Container.

To add the Update Onboarding State, create the file src/api/routes/admin/onboarding/update-status.ts with the following content:

src/api/routes/admin/onboarding/update-status.ts
import { Request, Response } from "express"
import { EntityManager } from "typeorm"
import OnboardingService from "../../../../services/onboarding"

export default async function updateOnboardingStatus(
req: Request,
res: Response
) {
const onboardingService: OnboardingService =
req.scope.resolve("onboardingService")
const manager: EntityManager = req.scope.resolve("manager")

const status = await manager.transaction(
async (transactionManager) => {
return await onboardingService
.withTransaction(transactionManager)
.update(req.body)
})

res.status(200).json({ status })
}

Notice how this endpoint uses the OnboardingService's update method to update the current onboarding state.

After creating the endpoints, you need to register them in a router and export the router for the Medusa core to load.

To do that, start by creating the file src/api/routes/admin/onboarding/index.ts with the following content:

src/api/routes/admin/onboarding/index.ts
import { wrapHandler } from "@medusajs/utils"
import { Router } from "express"
import getOnboardingStatus from "./get-status"
import updateOnboardingStatus from "./update-status"

const router = Router()

export default (adminRouter: Router) => {
adminRouter.use("/onboarding", router)

router.get("/", wrapHandler(getOnboardingStatus))
router.post("/", wrapHandler(updateOnboardingStatus))
}

This file creates a router that registers the Get Onboarding State and Update Onboarding State endpoints.

Next, create or change the content of the file src/api/routes/admin/index.ts to the following:

src/api/routes/admin/index.ts
import { Router } from "express"
import { wrapHandler } from "@medusajs/medusa"
import onboardingRoutes from "./onboarding"
import customRouteHandler from "./custom-route-handler"

// Initialize a custom router
const router = Router()

export function attachAdminRoutes(adminRouter: Router) {
// Attach our router to a custom path on the admin router
adminRouter.use("/custom", router)

// Define a GET endpoint on the root route of our custom path
router.get("/", wrapHandler(customRouteHandler))

// Attach routes for onboarding experience, defined separately
onboardingRoutes(adminRouter)
}

This file exports the router created in src/api/routes/admin/onboarding/index.ts.

Finally, create or change the content of the file src/api/index.ts to the following content:

src/api/index.ts
import { Router } from "express"
import cors from "cors"
import bodyParser from "body-parser"
import { authenticate, ConfigModule } from "@medusajs/medusa"
import { getConfigFile } from "medusa-core-utils"
import { attachStoreRoutes } from "./routes/store"
import { attachAdminRoutes } from "./routes/admin"

export default (rootDirectory: string): Router | Router[] => {
// Read currently-loaded medusa config
const { configModule } = getConfigFile<ConfigModule>(
rootDirectory,
"medusa-config"
)
const { projectConfig } = configModule

// Set up our CORS options objects, based on config
const storeCorsOptions = {
origin: projectConfig.store_cors.split(","),
credentials: true,
}

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

// Set up express router
const router = Router()

// Set up root routes for store and admin endpoints,
// with appropriate CORS settings
router.use(
"/store",
cors(storeCorsOptions),
bodyParser.json()
)
router.use(
"/admin",
cors(adminCorsOptions),
bodyParser.json()
)

// Add authentication to all admin routes *except*
// auth and account invite ones
router.use(
/\/admin\/((?!auth)(?!invites).*)/,
authenticate()
)

// Set up routers for store and admin endpoints
const storeRouter = Router()
const adminRouter = Router()

// Attach these routers to the root routes
router.use("/store", storeRouter)
router.use("/admin", adminRouter)

// Attach custom routes to these routers
attachStoreRoutes(storeRouter)
attachAdminRoutes(adminRouter)

return router
}

This is the file that the Medusa core loads the endpoints from. In this file, you export a router that registers store and admin endpoints, including the onboarding endpoints you just added.

You can learn more about endpoints in this documentation.


Step 2: Create Onboarding Widget

In this step, you’ll create the onboarding widget with a general implementation. Some implementation details will be added later in the tutorial.

Create the file src/admin/widgets/onboarding-flow/onboarding-flow.tsx with the following content:

src/admin/widgets/onboarding-flow/onboarding-flow.tsx
import React, {
useState,
useEffect,
} from "react"
import {
Container,
} from "../../components/shared/container"
import Button from "../../components/shared/button"
import {
WidgetConfig,
} from "@medusajs/admin"
import Accordion from "../../components/shared/accordion"
import GetStartedIcon from "../../components/shared/icons/get-started-icon"
import {
OnboardingState,
} from "../../../models/onboarding"
import {
useNavigate,
} from "react-router-dom"
import {
AdminOnboardingUpdateStateReq,
OnboardingStateRes,
UpdateOnboardingStateInput,
} from "../../../types/onboarding"

type STEP_ID =
| "create_product"
| "preview_product"
| "create_order"
| "setup_finished";

export type StepContentProps = any & {
onNext?: Function;
isComplete?: boolean;
data?: OnboardingState;
} & any;

type Step = {
id: STEP_ID;
title: string;
component: React.FC<StepContentProps>;
onNext?: Function;
};

const STEP_FLOW: STEP_ID[] = [
"create_product",
"preview_product",
"create_order",
"setup_finished",
]

const OnboardingFlow = (props: any) => {
const navigate = useNavigate()

// TODO change based on state in backend
const currentStep: STEP_ID | undefined = "create_product" as STEP_ID

const [openStep, setOpenStep] = useState(currentStep)
const [completed, setCompleted] = useState(false)

useEffect(() => {
setOpenStep(currentStep)
if (currentStep === STEP_FLOW[STEP_FLOW.length - 1]) {setCompleted(true)}
}, [currentStep])

const updateServerState = (payload: any) => {
// TODO update state in the backend
}

const onStart = () => {
// TODO update state in the backend
navigate(`/a/products`)
}

const setStepComplete = ({
step_id,
extraData,
onComplete,
}: {
step_id: STEP_ID;
extraData?: UpdateOnboardingStateInput;
onComplete?: () => void;
}) => {
// TODO update state in the backend
}

const goToProductView = (product: any) => {
setStepComplete({
step_id: "create_product",
extraData: { product_id: product.id },
onComplete: () => navigate(`/a/products/${product.id}`),
})
}

const goToOrders = () => {
setStepComplete({
step_id: "preview_product",
onComplete: () => navigate(`/a/orders`),
})
}

const goToOrderView = (order: any) => {
setStepComplete({
step_id: "create_order",
onComplete: () => navigate(`/a/orders/${order.id}`),
})
}

const onComplete = () => {
setCompleted(true)
}

const onHide = () => {
updateServerState({ is_complete: true })
}

// TODO add steps
const Steps: Step[] = []

const isStepComplete = (step_id: STEP_ID) =>
STEP_FLOW.indexOf(currentStep) > STEP_FLOW.indexOf(step_id)

return (
<>
<Container>
<Accordion
type="single"
className="my-3"
value={openStep}
onValueChange={(value) => setOpenStep(value as STEP_ID)}
>
<div className="flex items-center">
<div className="mr-5">
<GetStartedIcon />
</div>
{!completed ? (
<>
<div>
<h1 className="font-semibold text-lg">Get started</h1>
<p>
Learn the basics of Medusa by creating your first order.
</p>
</div>
<div className="ml-auto flex items-start gap-2">
{currentStep ? (
<>
{currentStep === STEP_FLOW[STEP_FLOW.length - 1] ? (
<Button
variant="primary"
size="small"
onClick={() => onComplete()}
>
Complete Setup
</Button>
) : (
<Button
variant="secondary"
size="small"
onClick={() => onHide()}
>
Cancel Setup
</Button>
)}
</>
) : (
<>
<Button
variant="secondary"
size="small"
onClick={() => onHide()}
>
Close
</Button>
<Button
variant="primary"
size="small"
onClick={() => onStart()}
>
Begin setup
</Button>
</>
)}
</div>
</>
) : (
<>
<div>
<h1 className="font-semibold text-lg">
Thank you for completing the setup guide!
</h1>
<p>
This whole experience was built using our new{" "}
<strong>widgets</strong> feature.
<br /> You can find out more details and build your own by
following{" "}
<a
href="https://docs.medusajs.com/"
target="_blank"
className="text-blue-500 font-semibold" rel="noreferrer"
>
our guide
</a>
.
</p>
</div>
<div className="ml-auto flex items-start gap-2">
<Button
variant="secondary"
size="small"
onClick={() => onHide()}
>
Close
</Button>
</div>
</>
)}
</div>
{
<div className="mt-5">
{(!completed ? Steps : Steps.slice(-1)).map((step, index) => {
const isComplete = isStepComplete(step.id)
const isCurrent = currentStep === step.id
return (
<Accordion.Item
title={step.title}
value={step.id}
headingSize="medium"
active={isCurrent}
complete={isComplete}
disabled={!isComplete && !isCurrent}
key={index}
{...(!isComplete &&
!isCurrent && {
customTrigger: <></>,
})}
>
<div className="py-3 px-11 text-gray-500">
<step.component
onNext={step.onNext}
isComplete={isComplete}
// TODO pass data
{...props}
/>
</div>
</Accordion.Item>
)
})}
</div>
}
</Accordion>
</Container>
</>
)
}

export const config: WidgetConfig = {
zone: [
"product.list.before",
"product.details.before",
"order.list.before",
"order.details.before",
],
}

export default OnboardingFlow

There are three important details to ensure that Medusa reads this file as a widget:

  1. The file is placed under the src/admin/widget directory.
  2. The file exports a config object of type WidgetConfig, which is imported from @medusajs/admin.
  3. The file default exports a React component, which in this case is OnboardingFlow

The extension uses react-router-dom, which is available as a dependency of the @medusajs/admin package, to navigate to other pages in the dashboard.

The OnboardingFlow widget also implements functionalities related to handling the steps of the onboarding flow, including navigating between them and updating the current step in the backend. Some parts are left as TODO until you add the components for each step, and you implement customizations in the backend.

You can learn more about Admin Widgets in this documentation.


Step 3: Create Step Components

In this section, you’ll create the components for each step in the onboarding flow. You’ll then update the OnboardingFlow widget to use these components.

After creating the above components, import them at the top of src/admin/widgets/onboarding-flow/onboarding-flow.tsx:

src/admin/widgets/onboarding-flow/onboarding-flow.tsx
import ProductsList from "../../components/onboarding-flow/products/products-list"
import ProductDetail from "../../components/onboarding-flow/products/product-detail"
import OrdersList from "../../components/onboarding-flow/orders/orders-list"
import OrderDetail from "../../components/onboarding-flow/orders/order-detail"

Then, replace the initialization of the Steps variable within the OnboardingFlow widget with the following:

src/admin/widgets/onboarding-flow/onboarding-flow.tsx
// TODO add steps
const Steps: Step[] = [
{
id: "create_product",
title: "Create Product",
component: ProductsList,
onNext: goToProductView,
},
{
id: "preview_product",
title: "Preview Product",
component: ProductDetail,
onNext: goToOrders,
},
{
id: "create_order",
title: "Create an Order",
component: OrdersList,
onNext: goToOrderView,
},
{
id: "setup_finished",
title: "Setup Finished: Start developing with Medusa",
component: OrderDetail,
},
]

The next step is to retrieve the current step of the onboarding flow from the Medusa backend.


Step 4: Use Endpoints From Widget

In this section, you’ll implement the TODOs in the OnboardingFlow that require communicating with the backend.

There are different ways you can consume custom backend endpoints. The Medusa React library provides utility methods that allow you to create hooks similar to those available by default in the library. You can then utilize these hooks to send requests to custom backend endpoints.

Add the following imports at the top of src/admin/widgets/onboarding-flow/onboarding-flow.tsx:

src/admin/widgets/onboarding-flow/onboarding-flow.tsx
import {
useAdminCustomPost,
useAdminCustomQuery,
} from "medusa-react"

Next, add the following at the top of the OnboardingFlow component:

src/admin/widgets/onboarding-flow/onboarding-flow.tsx
const OnboardingFlow = (props: any) => {
const QUERY_KEY = ["onboarding_state"]
const { data, isLoading } = useAdminCustomQuery<
undefined,
OnboardingStateRes
>("/onboarding", QUERY_KEY)
const { mutate } = useAdminCustomPost<
AdminOnboardingUpdateStateReq,
OnboardingStateRes
>("/onboarding", QUERY_KEY)

// ...
}

Learn more about the available custom hooks such as useAdminCustomPost and useAdminCustomQuery in the Medusa React documentation.

data now holds the current onboarding state from the backend, and mutate can be used to update the onboarding state in the backend.

After that, replace the declarations within OnboardingFlow that had a TODO comment with the following:

src/admin/widgets/onboarding-flow/onboarding-flow.tsx
const OnboardingFlow = (props: ExtensionProps) => {
// ...
const currentStep: STEP_ID | undefined = data?.status
?.current_step as STEP_ID

if (
!isLoading &&
data?.status?.is_complete &&
!localStorage.getItem("override_onboarding_finish")
)
{return null}

const updateServerState = (
payload: UpdateOnboardingStateInput,
onSuccess: () => void = () => {}
) => {
mutate(payload, { onSuccess })
}

const onStart = () => {
updateServerState({ current_step: STEP_FLOW[0] })
navigate(`/a/products`)
}

const setStepComplete = ({
step_id,
extraData,
onComplete,
}: {
step_id: STEP_ID;
extraData?: UpdateOnboardingStateInput;
onComplete?: () => void;
}) => {
const next = STEP_FLOW[
STEP_FLOW.findIndex((step) => step === step_id) + 1
]
updateServerState({
current_step: next,
...extraData,
}, onComplete)
}

// ...
}

currentStep now holds the current step retrieve from the backend; updateServerState updates the current step in the backend; onStart updates the current step in the backend to the first step; and setStepComplete completes the current step by updating the current step in the backend to the following step.

Finally, in the returned JSX, update the TODO in the <step.component> component to pass the component the necessary data:

src/admin/widgets/onboarding-flow/onboarding-flow.tsx
<step.component
onNext={step.onNext}
isComplete={isComplete}
data={data?.status}
{...props}
/>

Step 5: Test it Out

You’ve now implemented everything necessary for the onboarding flow! You can test it out by building the changes and running the develop command:

npm run build
npx medusa develop

If you open the admin at localhost:7001 and log in, you’ll see the onboarding widget in the Products listing page. You can try using it and see your implementation in action!


Next Steps: Continue Development

Was this section helpful?