In this video we're going to build an e-commerce platform powered by Medusa now Medusa is an open-source Commerce platform that has a built-in engine or a framework for customization now it's open source meaning that it's an open source Library you can download it host it locally or host it for your own or you can use the hosted version of Medusa which we're going to get into at the end it is a Platform meaning that it gives you a backend server an admin dashboard that you can use to manage your store data your products your orders
and whatnot we're going to walk through um the setup and you're going to see this in action and the last part is that it also comes with a built-in engine or a framework in version two that allows you to extend the data models and customize the features or this Commerce modules to whatever business logic that you want Which is an exciting part of this library that we're going to talk about today so let me just change this screen so I have more space here so we can dive into the documentation and see how this is
going to work we're going to build an application together a backend server an admin dashboard and also a nextjs front end or a storefront that connects and communicates with our backend API together and then through this setup We're going to learn about different features that Medusa provides now before we dive into the setup I just want to to mention the new architecture in version two which is decoupled modules this is going to allow you for greater flexibility and customizability meaning that each module or the Logics inside of your Commerce back end is now isolated into
separated modules let me show you what I mean by this now down here you can see we have different modules for Example in the category of cart and purchases we have a cart module we have customer modules payment module we have products pricing regions order management now all of the functionality that Medusa provides is provided through this isolated independent modules that you can use in different parts of your application you can even replace them with your own custom module so it's interchangeable with your own custom Module that allows you to extend the functionality and the
Medusa backend or the servey is going to orchestrate all of these modules together giving you um that functionality that you need for your Commerce now I think that's a very cool feature that makes Medusa a flexible and extendable Commerce provider now with that let's just go to our documentation uh there's going to be a Medusa version 2 um documentation specifically guiding you through the features inside version two now right now um the version two is in release candidate you're going to have to pass in this release candidate at the end of your Medusa by the
time this video is launched uh the version two is also launched and you can just run at latest now I have a little note here for myself too just summarizing what we're going to be going through here from a high level so before Setting up let me just go through the notes here as I mentioned Medusa is an open source Commerce platform with a built-in framework for customization we're going to see this in action where we talk about different modules and different functionality in Medusa and you would have a better understanding by the end of
this tutorial now it provides essential building blocks to create a powerful Commerce store that fits any business so you would have the essential Building blocks of any Commerce application such as product card ordering and stuff but you can also extend and create your own modules that is going to be plugged inside of this uh synchronized or orchestrated uh backend system now these building blocks are mainly uh two part or two different categories one is the Commerce modules as as I have shown you there are different modules such as products Orders and carts that help you
build um your Commerce functionality and there's also a core package which is responsible for orchestrating these different modules together and also allows you to extend modules create new tables create links between different tables expose API end points to then um expose this functionality to third party applications to your storefront to your admin dashboard so the core package is the server or the built-in in engine That we talked about that allows you to do to actually deliver this customization now the core package is a server has two main objectives first is to orchestrate the custom Commerce
modules or the Commerce modules that comes built in with Medusa and also to expose a rest API endpoints Now API endpoints is the main way that you would you going to expose functionality to any service that wants to use your Commerce backend whether it be an app a Storefront or your admin dashboard so this is another feature of our server backend that exposes this API endpoints now the core package also holds the logic that allows developers to extend and add custom API routes along with other available customizations we're going to see this again more in
action what can you build with Medusa well you can build any e-commerce um Experience Store you can build a marketplace where sellers and Buyers can come and meet each other something like um Amazon subscription businesses so this has a builtin module you can extend it to whatever um logic that you want order management system B2B store point of sale or pause so there are different things that you can build with Medusa really the the um sky is the ceiling um in terms of the setup we can go back to the documentation that we have we're
going to prepare our Environment which we need a not J base version 20 plus for version two you need git for your uh Version Control and then we need postest because Medusa is going to use postest qql to store data for your Commerce system so you need to have either a local postgress um database or a hosted version that Medusa can use during your setup now there's a link here in the description uh to the postest website depending on your um local machine you Can use Mac OS or Windows to install a local postrest version
I've already gone ahead and selected Windows my machine is a Windows I've selected the windows and installed a local postest during the installation you can select uh a password that Medusa is going to also ask you the first time that you install it to be able to connect to your postgress so once you have done that you're able to actually go ahead with the installation command and then from This point on we're going to install the back end the admin dashboard and optionally an EXs um storefront and then we're going to walk through an a
toz of a product order and what you get in the admin dashboard and then we're going to talk about the architecture and the file system different folders and different functionalities that comes with Medusa so let's go back inside of the documentation in here so we opened up This part let me close that part and also close this one so to get started we prepared our environment now we're going to run this create Medusa app at RC so I'm going to copy this command inside of a Medusa folder that I've already created now this is going
to ask you a couple of questions in how you want to set up your Medusa application the first thing is what is the name I'm going to give it a name of Commerce it asks you whether or not you want to also install The nextjs storefront again we installing the server it comes with an admin dashboard but you can optionally also have a nextjs front end or storefront that connects to your uh back end so I'm going to select yes to also see that it is asking me for postgress username to say postgress and then
give it a password I'm going to type in enter the database name can be anything here postgress I've already installed this Application before with that name so it is asking me for a new name okay now this is going to take a while to install the back end the server the admin dashboard and also the next jss storefront so I'm going to pause the video wait for this to finish and then I'll be back okay this should be done in any moment once this actually goes through and finishes it automatically redirects you and opens up
a browser Page for you to create your admin user so it opens up the admin dashboard and allows you to also create a user to be able to connect to your backend server so let's see this in action now okay so we're going to create a test user admin at Medusa test.com give it a name a password and then create an account we can start a Medusa admin with the same user that we just created and Now you are logged into your admin dashboard as you can see here um it has been seeded with some
sample products and a page for referencing our orders we're going to go through an order and actually see this in here inventories customers promotions and price lists that you can Define there are different settings you can have for your store from name regions um tax Configurations sales channels and whatnot there's going to be different user guides uh that I'm going to link in the description below or inside the documentation on Medusa website for how to use your admin dashboard or how you can use these different settings we're not going to talk about those um in
this video but we going to have links in the description or future videos that we're going to walk you through different things that You can do inside your admin dashboard so let's go back inside of our application now after running this script command if you look at the left hand side it has created a Commerce that's what I named my back end Commerce and also the Commerce storefront which is going to be my nextjs application now let's also run the nextjs application so we see our storefront as well so here I'm going to just go
to the Commerce Storefront now here I can run npm runev this is an xj's app we're going to look at the file structure in a second now okay it seems like this process that we are running here it's already starting our um next J storefront as well so let me just go into our Commerce backend here so this is the Commerce backend I'm going to mpm run diff here this is going to run our admin dashboard on Local Host Port 9000 and for/ app that's where you can actually access Your admin dashboard as we were
doing it here up on the app on 9,000 but now that we have this running in a separate process maybe I can clear this out and npm run Dev this is going to separately run uh the storefront which is an xjs app on Local Host 8000 which is going to communicate to our back end via API routes or API calls so let's see this in action as well and then we're going to jump into the code and I'm going to show you the nextjs Front end from a high level then we're going to jump inside
of our own back end and then talk about the file structure and different functionality that comes inside your Medusa server and then we're going to continue in the docks there so this is our Medusa store frontend I'm going to make it a bit smaller so you can see it from a higher level let me make this big again so you can have go to the menu in the store as I mentioned your database has been Seated with some sample products as you can see here so you can go on a specific product for example to
see different images it comes with a beautiful and minimal design for your storefront you can customize it to your needs you can even connect it to your own storefront it doesn't need to be nextra as it can be any any storefront for that matter it's at the end of the day talking to your backend via API so you can just have whatever storefront or Framework that you like to build your storefront with so let's go through an order here so I'm going to select the size add this to cart it has this nice cart module
that pops up when you hover over the cart you can go to your cart uh let me make this a bit smaller so you have your product selected you can proceed to checkout from here you can put in your information and complete a checkout let's just give it a name and Address a post all code City maybe Copenhagen Denmark I'm not uh familiar with provinces in Denmark so email let's go Hamed test.com and let's continue to delivery we can Define different deliveries inside of our back end for now I'm just going to pick the standard
shipping for payments for testing purposes we're going to just go ahead with this manual Payment there is plugin in Medusa that works already with stripe and PayPal so you can just Define that as the config ins inside of your Medusa config to then uh enable stripe as your payment if that's uh what you want so we're going to just use the manual payment for development review and then we place the order this is going to redirect us to a thank you page that shows a success inside of our ordered then we're going to see or
go to the back end and see This so this is the thank you page the order was played successfully with the delivery and payment information now if I go back to my backend or admin dashboard if I go to orders here we go so the details of the order the product the payment who the customer is I'm going to make this a bit smaller so you can see what's going on uh from high level it has a very nice uh backend design and this is one of this uh one of the things that has been
Improved inside the version two it's a nicer back end um they have their own UI packages I'm going to mention it when we go in a few minutes further on into actually extending your admin dashboard now as you can see it comes with some pages and digets that you have here but you can extend your admin dashboard as well you can add pages to it you can add different vigs to this different pages we're going to do this um together and you can use the Medusa UI package to Have a similar design as what they
have here which is is inspired by shat CN and it is using RX UI under the hood so you get accessibility out of the box um with this UI package which is great now let's go back inside of our code and actually look at the projects from a high level Let's us start from the storefront as I mentioned this is a nextjs app if you've been following me on the channel you're probably familiar with nextjs but again this is optional you can build your Storefront with any any framework that you want your code is mainly
inside the source your pages are defined inside of the app router the country code is because Medusa supports different regions so you can have different regions different countries and it automatically picks up or or can redirect the user to the correct uh region in terms of uh the shipping or whether or not a specific product is available different warehouses that you Can Define different tax settings that you can set um so I'm going to leave this to you to explore more for um different features that you Medusa provides but these are mainly your different pages
inside of your nextjs app you're going to have a library F folder for context and hooks that works with your data modules is all of your components that are um working inside of your pages working with your back end and the apis inside of your Medusa back End you have your Styles Global Styles and a midle ver that's basically um getting the region and redirecting the user to a specific region if needs be this is a nextjs middle if you're not familiar with nextjs middle there's videos on the channel where I talk about the middle
ver specifically working with different locals in this case it's not a localist country code but it works the same way where we get the region Um from our settings and redirect the user from there so again from a high level this is a pretty standard nextjs app with the design that you just saw and some components that you can just go ahead and customize for yourself whether is creating new pages or customizing the components that it's already here you can just build on top of this storefront to accommodate any need or any design that you
have inside of your app now this was the Commerce storefront let's Go to the Commerce backend or the server side of our Medusa application again everything lives inside of your Source the admin is going to expose any custom um functionality that you would want to add to your admin dashboard the apis is for your API endpoints um Medusa comes with admin and store apis automatically or out of the box but you can extend and add different or more API endpoints to expose new functionality to Your storefront to your admin dashboard or to any third-party service
for that matter so this is how you would expose new API endpoints we're going to do this together so don't worry if it doesn't make sense right now jobs is to Define scheduled jobs or cron jobs that is going to run on specific intervals and it has access to your Commerce modules or to your back to your data so you can just do any scheduled tasks there you can provide links between different data Tables so that you can extend or build on top of Medusa's application or data models which is pretty powerful I'm going to
mention how this works now modules is U the building blocks of Medusa and how you actually add customization so anytime you want to extend models or extend functionalities you would create a module you can create models or data tables inside of your database you can export services that works with data tables and then expose This module through this Medusa container to the rest of your app that is just the synchronization engine between all the modules again this is a little abstract right now we're going to jump into the example and see this in action scripts
is any function or any script that you want to load subscribers Medusa works with the events so anytime an action is happening inside of your application such as the admin creating a product uh events are emitted and then You can Define subscriber functions that run once this specific events are running we're going to see the examples for this as well and workflows is a series of steps so imagine that you want to run a task that is a series of actions and queries now you would Define that inside of a workflow which is basically a
combination of multiple steps and what this gives you is the ability to first of all track back the progress of this workflow secondly it Enables you to run a roll back function so if any error happens you can roll back the step to make sure that your data is consistent and thirdly it automatically retries the failed steps so it's a more robust way of completing tasks specifically when they're multi-steps and when they're talking to third party services so you don't want to your data to be inconsistent between different Services if any error occurs so this
is from a high level how you Would extend your Medusa application the one file that I want to also mention is Medusa config this is where you would Define uh different config for your project such as your database URL and whatnot we're going to use this to also Define some modules in a little bit so with that let's actually go to our documentation and do this so we have set up our Medusa application and now the first thing that I want to do or what I want to cover here really is this basic Concepts in
Medusa that is going to introduce all the customization or flexibility that Medusa has in these basic concepts and then you can build whatever functionality that you want using this knowledge uh on your own so let's us start from the project convention we talked about the different folders that already exist in the source folder from the admin API jobs modules all the way to workflows and the Medusa config which is where you would just set Up your configurations let's start start from Medusa container now Medusa container is a concept um that is going to allow you
to use different services and modules inside of Medusa so it holds resources registered in the Medusa application such as different Services now you're going to use this container to resolve the services for example we have an API endpoint here it is defined with this get so it's a get API endpoint and inside of it I'm receiving this rec. scope which is that Medusa container I'm going to use the resolve method on it and resolve the product module so remember that this different functionality in Medusa comes in the form of independent isolated module such as product
module cart module or your own custom modules and they're all registered inside of this container and you can use the container to resolve This service and then use that service for example here inside of API endpoint you can use it inside of a workflow you can use it inside of your scheduled tasks for example so that's how you're going to uh this is the engine that actually synchronizes your services and different modules for example here we're getting the product module service and from here we're calling the list and count products to get a count Of
all the products that we have inside of our back end okay so just to test this out we can create this API endpoint so inside of our sources we can go to the API and I'm going to create a new route called count inside of it I'm going to create a route. TS we're going to have a specific section for creating API UT so I'm jumping a bit ahead but I want to show you how we using this Medusa container that lives inside of this Rec Do or request. scope to resolve the product module get
the count and then respond back so let's save this out once you save this route inside of your API this is how you create your backend serice side API end points if I open up Postman right now and go ahead and hit our API endpoint count this is going to give me the count or the total number of products I have right now so just as easy as that I created an API endpoint I Ed the container to resolve to my Product module this was a module that comes built in from Medusa and I got
all the counts of my products expose this functionality through an API endpoint a get request to the outside worldall now this can be my storefront this can be my admin dashboard or a third party service you get the idea now let's talk about modules now modules is a combination or a package of reusable functionality so you're going to package this functionality inside of A module now if can handle business logic in a class called services so when you create a module you also export a service that actually is the functionality or the business Logic for
this module it typically defines and manages data models and represents a table in the database as I mentioned Medusa comes with pre-built modules for your core Commerce such as a product cart shipping And whatnot but you can can also have your own custom modules or extend the modules that Medusa comes with now how to create a module well you can go inside the sources folder inside the modules modules directory and create a module for example hello here we're going to define a data model which represents how the table inside of our database is going to
look for this data model so this is the schema for a data model if you're using the model. defin Give it the name for this specific module so let's go to our modules me just close everything I'm going to go to Source I'm going to go to modules here I'm going to define a new module called hello okay now the first step is to create a data model inside of a models folder so that's what we're going to do we're going to to create a models Folder and inside of it we can create a custom
model let's say we name it custom. TS and we're going to paste in this code so let's just get this name it custom that's what I named my model so to this model. Define you pass in two parameters the first one is the name of the table it needs to be snake case in your postt database and the second one is the the schema or the shape of Records inside of this table so each one has an ID you're going to use The model function to Define this keys and then a name that's a text
I named this model custom and then I'm going to use this to expose some services to the outside to other uh parts of my application which is the next step so create a service now a module must Define a service that implements its functionalities such as managing the records of your custom data inside of your database so you're going to have to Create a file called service.ts there I copy this and then here we're going to define a service now I named this custom so let's rename it to custom now we're going to extend the
class that's created out of this Factory function so Medusa service it's going to receive a custom module so we created this custom sorry a custom data model that we just created in the last step we named it custom That's our custom data model we're going to pass this custom data model to this function this is going to create a class that has methods for updating creating reading order CR operation on this data model inside of our database so instead of having to recreate or reinvent a v for every custom model that you create you can
just extend this Medusa service that automatically creates this CR operation methods for you on this class that you're going to register inside of Your Medusa container and expose it to the rest of your app so that's creating the service now that we have the service we need to actually export this module definition so we're going to have an index file here. TS where we're going to define or export this module with the hello module name and actually a service that's pointing to the service we just created in the last step so we saying hey Medusa
if you Want to use this Custom Service that I created the service lives here you can expose this module and the services the functionalities with the rest of my app so we can use a Medusa container to then access to this specific Service as well so let's see from a high level here we created this hello inside of it there's this index that exports the module there's a service that creates the service by extending Medusa service and then there was this models folder where We Define a custom data model or a table instead of our
database that holds the functionality of this specific module that's how you create a custom module and expose its services to the rest of your application and of the ways that you can customize or extend Medusa now the last step to also register this inside of your container is to actually pass this point the path where this module lives to your Medusa config so let's Go sorry instead of our Medusa config we have this project config I'm going to also have some modules this is going to be an array of different modules which is an object
with a resolve property pointing to where this module lives so it's into Source modules and hello that's where we created it Source modules and hello now this is registered inside of our Medusa container and we can use it but before we are able to use it through this Module we have created a new data table so we have to run migrations to actually create these migration files and then actually migrate our our data base to create this new table with this schema that we defined so we're going to have to run this service so let's
open up our terminal stop the dev server clear this out and actually run npx Medusa DB generate for that hello module service so it's going to run or generate the Migrations necessary for this specific module that we created which is going to create a migrations folder inside of our module so hello now as this migrations now if you look at the migrations it's basically uh SQL script to create a new table and drop if it exists before so we have the necessary migrations now and the next step we can just run this migration to apply
the changes to our database so we're going to open up our terminal again and actually run the Migrate now this runs the migration for all of our modules now for the modules that we have not created any um updates it's a skipped because it is up toate but for the hello module service we have run the new migration and completed successfully which means our database now has a table corresponding to this custom data model that we created or the hello module okay now let's test this out since we now have registered this Inside of our
Medusa container we can access it inside of our API endpoint to get a hold of our hello module and maybe use the hello module services that we extended from Medusa services to create a new record inside of our database now this is a function that's automatically created on our service because we extended Medusa services and it just created this Crow operation for US creating updating deleting and whatnot and we're going to Generate a new record or a new row inside of our table and return that so let's create this API endpoint actually we're going to
have inside of our API we're going to create maybe a new um route that says hello inside of it I'm going to say route. TS and I'm going to copy this command here let's just close a terminal so we have enough space now this um Crow operations or CR Functions are mapped to your model because I named mine custom it's create customs with plural um this um is mapping to whatever name that you have put on your model so create Customs it's going to just create a custom or an instance of the custom data model
inside of our table with a name of test now just note that I have created an API endpoint this is how you create API endpoints you export functions that map To an HTTP HTTP ver like get here I'm receiving the request Medusa request and response just is like an Express endpoint or a middle ver that receives an a get request it has an instance of the request and response and some functionality on this instances for example on the request. scope we have the container we going to resolve our hello module on the Hello module service
we can call the create Customs to create a New record and then send it back okay so with this endpoint if I now go to my Postman and hit the hello endpoint we just created resend this okay here we go so it created a new record gave it an ID something that I forgot to mention when we were defining our custom data model is that uh by default it also has a created ad updated ad and a deleted ad property and that's what you're seeing here so the name was test that we passed the ID
the created ad and updated ad Fields were automatically also populated so we defined a new module this module had a custom um data model or a table we exposed some services that operates crowd operation on that data model or table we then then registered it with Medusa container run the migrations and then use the service inside the Medusa container in an API endpoint that we defined here to then to just create a new sample or instance of um this module in our inside of our Database okay so that's completing the test now why would you
use modules in Commerce you often need to introduce custom Behavior specific to your products to industry to your TCH stack or general ways of working in other chromas platforms introducing custom business logic and data models require setting up separate applications to manage these customizations Medusa removes this overhead by allowing you to easily Create and write custom models that integrate with the Medusa application without any implications on the existing setup of Medusa so when would you want to use modules whenever you want to create a new table to your database when where you want to extend
the existing tables in Medusa when you want to integrate with a third party system or any feature or if you wanted to reuse your custom Commerce features across Medusa applications you can just Define This modules that it allows you to even use them inside other environments such as Edge functions or your nextjs app now we've briefly TP uh touched on API routes uh API routes is how you would expose different features of your Commerce to external applications such as your storefront admin dashboard or third party systems now Medusa Medusa's core application provides the store and
admin apis out of the box if you go to the API You can see this admin and also the store this is what comes built in or the necessary apis functionality that your Commerce application needs out of the box but you can also create your custom API routes and expose your own has some functionalities which we have tried a couple of times at this point you you will create a route. TS or route. JS inside of the API in the source directory you would then export route Handler Functions that map to http method such as
get post delete and then from there you just export the functionality or just the logic that you want in this instance we're just returning a Json object with this message property you can just test out by running curl or in our case we just using Postman to um send a request to your backend which is living at Local Host Port 9000 and then hello world now one thing to note is that even though we Are creating these API endpoints inside inside the API folder the endpoint doesn't have the API path in your path so whatever
you put inside the API it just turns into an API endpoint with the path or the directory that you have defined and the actual API is not part of the path just something to note now when do you want to use API routes when when anytime that you want to expose custom functionality to be used by the consumers of your backend it being your Storefront admin dashboard or external applications you would use the API end points now as we mentioned Medusa comes with built incomer modules for a list of all the modules that's already in
inside of your Medusa applications such as cart customers inventory payments products regions taxes and whatnot you could just reference the documentation the way that you would resolve the Commerce module Services is through the Medusa container that we Have already talked about for example inside of your API endpoints you get access to the container on this request. scope you can then resolve to any of this uh Commerce modules that comes built into Medusa to then get the functionality that they provide such as this list and count that gives you a account of all of the products
now for the directory structure of a specific module we have already seen this in action together so we had The index which was exporting the module we had the service which defines the functionality that works with the data models of this specific module we had the models folder where defined a custom model that was the schema of our database the migrations was automatically generated when we we ran the migration command for Medusa to then actually generate some migration um scripts for us to be able to create this new database and we have something that Calls
loaders which we're going to uh talk about next this is functions that just run one time at the startup at the application startup um and that's how you would Define a module okay so let's go to loaders and see what loaders are well loaders are just functions that are executed it at the application start so if you want to run anything once when your Medusa backend starts you could put it inside of a loader this can be scoped to a Specific module so you can just organize the loaders or scripts that you want to run
at startup for example if you wanted to sync your data between Medusa and a third party service and you want to run this once when the Medusa starts you could put it inside of a loader how do you create a loader well you would just create a loaders loaders folder and a TS file inside of it that just exports a function that runs when the application starts once you define that you're going To BR bring this loader to your module definition and specify that your module actually has a loader so loaders are again scoped to
your module so you define the specific loader for your module okay so let's actually do this together so we going to go to our hello module create a loaders function and then a loader so let's go inside let me close the API go to the module hello I'm going to create a new folder called loaders and inside of this let's just Put in a hello. TS and I'm going to copy this code it's just going to log this into the console now that I have this I have to go back to my module definition which
is inside of my index and I have to say hey the service for this module was that and the loaders is this guy so I have to bring the hello world loader loader so hello there you have it so that's imported from my loaders now if I save This and open up the terminal we should be able to see this hello if you look at here where I highlighted it it's just hello module just to started the Medusa application so this uh function that be defined inside of our loader just ran at the start of
our application okay so we tested it out now when would you want to use loaders again when you're performing an action at application start and this is a onetime Um it's not something that reruns it just runs once so for example if you want to establish a onetime connection with an external system if you want to sync your data with an external system you can just run this now if you need something to run continuously or at a set time you can use scheduled jobs which we're going to cover later on uh which is like
uh scheduled Chron jobs that run on a specific intervals if this is something that needs to Rerun now the next thing that uh comes out of your Medusa backend is events and subscribers we touched on this briefly Medusa sub uh emits events when different things happen inside your Medusa backend for example if you create a new product it emits a product. created event you can subscribe to this event and run functions in response to this events to synchronize it maybe let's say you have a CMS a Content management system and you have your Medusa backend
anytime that you're creating a new product in your Medusa you want to also send some data to your CMS so you don't have to manually sync this it automatically responds to this and sends maybe a web hook to your CMS to just import this or create this product instead of your CMS as well some something as an example so again events actions performed in inside of Medusa they're going to sub emit this event and you can just subscribe to Them how are you going to create them well you can go to your subscribers directory create
a TS file export a Handler function and a config that says run this Handler when that event is happening so product. created okay so let's just copy this or maybe you're going to test it with a uh the more extensive example that we have down there so bear with me for a second so we need a Handler and a config that's all this is what runs when That event is triggered the config is also defining the event that the subscriber is listening to here is product. created now to test it out you can just go
ahead and create a new product we're going to do this in a second and in response to that you can just run that a product was created we're going to extend this by actually using other services inside of this Handler and this is uh what I meant by a More extensive example here now inside of this product Handler this subscriber function you have access to Medusa container on top of the event data so the event data is the event that was triggered so product created so we get the product data but we also get access
to Medusa container so we can result to any any other module that we want any other services that we want so for example here we are resolving the product Module so product module Services we are getting the ID of the product that was just created out of the data that's passed to our event and then we're going to use the product module service to retrieve the product with this ID and like for example here we just logging the product title but you get the idea the point I was trying to make is inside of this
Subscriber Handler functions you have access to Medusa container which is basically access to all the functionality or the modules custom builtin inside of your Medusa backend which makes them very powerful okay so let's actually create this one so I'm going to create a subscriber product created so let's go to our subscribers create a new file let's say product created. TS let's copy the code here close the Terminal for a second so again this is the same code that we had there anytime uh that a product is created this function is going to run is going
to use the container to get a hang of our product module service use the data that was passed inside of our event from Medusa to retrieve the product and then log the title of it okay so we have this subscriber right now registered now all I need to do is to go back to my application go to My admin dashboard let's refresh this let's go to our products and actually create a new product let's go to products and let's create a new product because the event we defined is product created so winter jacket well when
you're defining the product um you can pass subtitle you can pass a slug or handle as they call it this can also be automatically generated if you leave it empty a description you can upload images you can Define different variants For this product for now I'm just going to continue with a name uh but you as you see there's different options that you can fill in here such as the type category collections tags and whatnot this is going to enable you to then uh search or filter based on different categories inside of your admin Dash
or your storefront you can Define different sales channels so it can be online it can be in store so you have this functionality out of the box with my Which is great and then I'm going to publish this product so I have this winter jacket product created now if I go back to my application and in my console uh what I should be able to see is these two lines first of all the info runs that says processing product. created which has one subscriber so we have registered a subscriber that responds to product I created
and then I have the product winter jacket which is the title that I gave to the product Logged into the console which is what we were doing inside of this Handler function by logging this here but you get the idea you can just extend your um application through this custom subscribers that respond to different events and synchronize your data inside of from Medusa with external applications or do anything that's necessary here really to process this this task so let's go back to the Docs now for a list of all the events that are emitted in
your Medusa backend there is a reference here so preference documentation for the list and next we're going to talk about SK scheduled jobs which are basically Crown jobs running inside of your Medusa server which is great because not only it gives you a scheduled Crown job capability but it also has access to your Medusa container which means all of your custom modules or built-in Commerce modules Inside of your Medusa back end how do you create schedule jobs where you go to the folder jobs you create a TS file you export a function and a config
option that says what's the name of this job and what is a Chron expression or how often should this run for example here just loging hello and then we running it every minute we're calling it every minute message okay a simple example of running a Chron job when your Medusa backend is Running now you can also extend it as I said you have access to your Medusa services so your cron um job or your job's function has access to this container which is Medusa container you can use it again you get the idea this is
a similar pattern that we've seen in all of the functions that we've seen so far for so we use the container resolve the module product and then here we're just using the product module service to get the list and count products function Get the count okay but you get the idea this is this can be you know synchronizing your products with an external service maybe running internal tasks every minute for example here uh as an example it says if you want to let's say synchronize your inventory with an Erp solution or enterprise resource planning solution
once a day you can just set it in your scheduled jobs this is going to run and sync the to Services together for Example so here um if you're just logging our products let's actually run this every minute and see how this works to test this out so inside of our jobs folder so Commerce Source jobs I'm going to create a new file called um maybe count because we're counting products to that TS inside of it I'm going to paste this let me just close the terminal for a second so again it's a custom job
running it's a function that runs every Minute because I have defined it inside of this config it retrieves the product module service the count of all of my products and then just logs it into the console okay so let's open up our terminal now and and we should be able to see this logging any minute cuz this runs every minute and we should see a log of the total number of counts of our products we initially started with four products we created one of our own so um I'm Assuming that we have now five products
and we should see this log at any point here there we go time to check products you have five products and as I mentioned this runs if minutes so and on the minute passes this can run again you can set it to run every hour once a day you get the idea this is a um Regular Chron expression that you can pass in here to Define how frequently this job needs to run now last thing that it's also very Exciting feature in Medusa it's the concept of workflows we touched on this really briefly um it
is to complete a series of tasks and quy so anytime that you're running a multi-step task that has different steps or talks to different external services to make it more durable more stable and error prone you would want to run it inside of a workflow which defines this tasks into different steps so that you can track the progress of each step you can roll Back if they encounter an error for data consistency and it retries automatically every failed step which is a great feature that you often find in external Services uh from providers that provide
like different workflows triggers and uh queing services or messaging services for you to Define different workflows this comes built in uh in Medusa which is great in my opinion now how would you execute a workflow well we create steps as I mentioned using the create step Function from the um SDK and then you would Define or combine this steps into a workflow so you would call this create workflow function and then you would just export a function with this different steps and then finally return a workflow response which is going to be the response returned
back to whoever executed this workflow now you can execute your workflow from inside an API route from an inside a subscriber Function a scheduled job any task that you want to perform in your Medusa back end it's a good idea to do it inside of a workflow because it gives you that data consistency that roll back functionality and also it retries uh the different steps if they fail so you can make sure that a task is completed correctly when it is actually completed now again you have access to this is just showing how you would
execute uh your workflow so here we're Going to pass our container to our workflow for example here if you're calling our workflow from inside of an API end point can be triggered via a web hook that just then triggers this workflow inside of our application so you pass it the container and then you would call The Run function on it your workflow can expect also inputs so you can pass any input that you've defined before and pass the input here Okay now as I mentioned you can also inside of each step access the context object
and the Medusa container on it to resolve to any services so step one here let's say we are creating we are counting the products again VI are resolving the product module service and this function on it to get the count so you have access to your Medusa container and therefore all of the functionality or custom modules and commerce modules built-in modules in Your Medusa inside of your workflow steps as well which makes them very powerful so let's test this together let's go up where we're defining these different steps so we're going to create these different
steps so let's just copy this I'm going to go to my workflows folder just close this workflows I'm going to create one that says let's say hello okay I'm going to put an Index.ts here this is where I'm going to define the workflow I'm going to separate my steps into a folder called steps then here I'm going to include an index.js file the TS file where I'm going to Define my steps me close this files and so we know what we're doing so let's go this is where we're defining our steps so our first step
is calling this create step just just returning a string you can do anything you want here in step really You pass it a function and then you can Define any functionality that you need here okay um here it defined a second step as well so for the Second Step our second step actually this is the function that gets executed when you execute the Second Step it requires an input so it it is expecting an object with a name property good now we want to create our workflow so we're going to copy this go back inside
of the index that we're exporting From this hello workflow and here is where I'm going to have my workflows okay so let's get this workflow input just for the sake of Simplicity I'm going to copy them both in here and I'm going to say you know my workflow requires this input that I'm going to then pass to Second Step cuz remember our second step was expecting an input okay that's just saying that now step one and step two we need to Export this steps because I've put them inside of a different file I can export
them you can also Define them inside the same file it is just for organization purposes that I put them inside the steps there's no requirement you can just Define them inside of the workflow file Al together now I can uh import these step one and step two so what's happening here we are creating a workflow we're calling it hello work hello world and we're passing a function That's running anytime anyone executes this workflow this function needs an input it runs step one get the response runs step two passes the input gets the response and then
finally returns a workflow response which is then returned to whoever executes this workflow so far so good let's go back and let's actually execute our workflow now let's imagine that we're executing this workflow from an API route you can again run it from inside of a subscriber and Scheduled job for Simplicity I'm just going to execute this workflow from inside of an API get um API route so let's go ahead and create an API input Point called workflow so inside of our apis this is going to create a server API endpoint for us I'm going
to name this um workflow inside of it we need a route. TS file uh we named this hello so let's just leave that hello save okay so API Endpoint a get request it's executing the my workflow we are ex importing from the workflow we just created VI are passing the Medusa container to it that's how you execute your workflows and you call the Run function on it now because we are expecting an input I'm passing in an input properly into that object and our my input as I defined it here is this an object with
a name property so I'm defining it here as well an object with A name property and I'm getting this name uh from the query parameters on the request that came into my endpoint okay and then I'm going to send the result back now this workflow what does it do it executes the first step passes the input to Second Step and then Returns the respond of our first step as a message so just test this out if I go and open up my Postman now let's go here and open up postman on top of it Okay
so now if I go to my workflow endpoint I just created see I get a message back hello from step one that's what I've defined inside of my step one just says hello from step one now let's return inside of our workflow instead of returning the response from Step One let's return this uh the response from step two okay let's see what happens here so send again so hello undefined from step two now step two if we look at It it needs a name to be passed to it because we don't have it it's undefined
now how do we pass this name to it well inide of our workflow whatever input you pass to when you're executing this workflow it's passed to our second step now who is executing our workflow we're inside of our get request this is where we running the Run function to execute this workflow we're passing this input from it which is coming from our request Query prer so if I go back and then pass in a query parameter name equals HED then send the reest it says hello on from step two now this is just to show
a simple example just to show that how powerful the workflows are in that you can Define different steps you can pass inputs to your workflow pass the inputs to your different steps get the uh response of one step plugged into the next step and complete a series of tasks in a way um Uh that's trackable and Al also you can roll it back back if an error happens now let me show you how you would Define a step with a roll back now let's say this first step that we created the first parameter we pass
to it is the name of our step the second parameter is the function that gets executed whenever we execute this first Sy step but it doesn't stop here you can pass in another function and this function is your Compensation function or roll back function so anytime this step encounters any error this function is um executed so let's say inside of here we are creating a new um instance of our custom model of our product of our brand model that we just created and something went wrong and we want to delete that whatever or reverse roll
back whatever happened inside of this step so you export another function from each step that's Your compensation function or roll back function and you can pass data to this so whenever you are returning this new response the first parameter is the response of this step but you can also pass in a second parameter let's say I'm passing in an ID this is then passed in to your roll back function so this is going to then expect an ID of type string it also gets the container inside of the uh context object so it can talk
to an eCommerce Module any of your database tables to reverse whatever happened inside of this step and that I think is very powerful that comes built in to your Medusa workflows and on top of this you get the automatic reply automatic retries anytime that you encounter any errors and that's workflows now the last thing I want to talk about is this basic concepts in Medusa is actually customizing your admin dashboard as I mentioned you can add pages or vids to Your admin dashboard wigets uh wigets are just um components that you can add to your
current pages so let's say we want to create a product widget inside of our product pages you can go to your admin folder this is anything related to your admin backend or admin dashboard inside of the vget you be going to add a product widget and then export this component uh which is going to insert this widget into our product detail page Before any other section so on top of the product widget that we can see together so let's go inside of our source uh and admin we're going to create a widget and rename this
to widgets then here I'm going to have a file that says product widget. TSX and let's copy this so what are we doing here this is just a react component with some UI elements from Medusa UI and then a config that says where to insert this specific component so the zone is product page detail page and before which means before any other section so this should add this heading to our product detail page so let's save this go back to our back end and if I go to products so if I open up a new
product and refresh this okay so let's go back and see what We've done wrong here okay so uh okay my bad I have defined this uh video it's inside of the API it's actually inside of the admins sorry so let's move this up there okay so let's just look at it from high level we have this admin we have this API inside of the API we have the admin as well this is the admin and the store API endpoints but that's not where we want to export our widgets the admin folder is where you would
work with your Admin backend so you create a viget folder here and a component with a zone now if I go back to my app and refresh this should be shown on top of all the sections okay here so product viget is now added this section is the custom vet that we just created that's now living inside of our product detail Pages you can also create UI routes or Pages here inside of your admin so it's very customizable we're not going to um Cover that here but if you follow the documentation here there's this customization
section where it uses all the concepts that we just talked about to create a new module called brand now right now our product doesn't have a brand field let's say in our custom Commerce solution we want to also give every product a brand and then also enable users or your admin users to filter based on this brand so if you're going to create a brand module then You're going to create a workflow that actually uh responds to an API request to create a new brand you're going to link this brand to your product table so
your products now can have a brand ID set on them you're going to learn how to query these different links and then you're going to customize the admin dashboard to add a viget that shows the actual brand on the product detail page and also have a UI route or a page dedicated for your Brands where you can Just see different brands or different brands products belonging to different brands it also talks about integrating or using the same same concept of your custom module to integrate with different services for example you can just connect your Medusa
backend to your CMS and communicate between the two through your custom module handle events schedule tasks and whatnot which uh hopefully we're going to cover in a future video where we dive deeper into An example of customizing or extending your Medusa backend through the same Concepts that we reviewed here together and that's a wrap for this video folks we covered a lot of Concepts and grounds in Medusa but from a high level Medusa is a modular Commerce platform with a built-in engine for customization it exposes all the Commerce logic through independent isolated modules that can
be used on their own plugged into each other or Even changed or replaced with your own custom modules that backend framework or the customization engine allows you to Define different models and modules different tables link them with current Commerce modules and expose them through API endpoints to your storefront to your admin backend and to external Services which makes Medusa very extendable and customizable which is a great uh feature for any Commerce provider cuz oftentimes when you are building Commerce Applications you want to have specific uh business logic that that applies to a specific industry and
instead of having to fight against U the platform that you're using if you can just build on top of it extended it it is going to reduce your development time drastically and make it easier to apply this or fit this solution to any business logic or domain out there now before we wrap this I want to also talk about deployment really quickly Here our Medusa application is uh consisting of two parts one is our Medusa application or backend which is our server and admin dashboard which are tied together into one application they can be deployed
separately or they can be deployed as one service to any runtime that runs node.js because at the end of the day this is a node.js server running and then you have one or more of your storefronts connecting to this back end through the apis now for the Medusa Application or your back end you can deploy to any hosting provider that has no JS it also has to support postgress database and redist these are the services that Medusa uses internally to store your data so platforms like digital ocean Railway or AWS have this another option is
Medusa Cloud which is a hosted service for Medusa applications that's tailored toward Medusa you can sign up on the site to get access to Medusa Cloud if um you want to have a Endtoend hosting service that supports your Medusa backend and as I mentioned your storefront is just going to be any application or framework that you choose in our case was a nextjs you can applo you can deploy it to versel for example as a provider for nextjs that's as far as deployment goes I wanted to mention this we didn't deploy this here maybe we
have future videos that we talk about deployment customizations and other uh you know different Logics that we can Implement inside of our medal application if you have any questions like always uh hit me up in the comments there's going to be Link in the descriptions for documentations and references that I use inside of this video and I'll see you in the next one bye-bye