Documentation

3.7. Loaders

In this chapter, you’ll learn about loaders and how to use them.

What is a Loader?#

A loader is a function executed when the Medusa application starts. You define and export it in a module.

Loaders are useful to perform a task at the application start-up, such as to sync data between Medusa and a third-pary service.


How to Create a Loader?#

A loader is created in a TypeScript or JavaScript file under a module's loaders directory.

For example, create the file src/modules/hello/loaders/hello-world.ts with the following content:

src/modules/hello/loaders/hello-world.ts
1export default async function helloWorldLoader() {2  console.log(3    "[HELLO MODULE] Just started the Medusa application!"4  )5}

Export Loader in Module Definition#

Import the loader in src/modules/hello/index.ts and export it in the module's definition:

src/modules/hello/index.ts
1// other imports...2import helloWorldLoader from "./loaders/hello-world"3
4export default Module("hello", {5  // ...6  loaders: [helloWorldLoader],7})

The value of the loaders property is an array of loader functions.


Test the Loader#

Start the Medusa application:

Among the messages logged in the terminal, you’ll see the following message:

Terminal
[HELLO MODULE] Just started the Medusa application!

When to Use Loaders#

Use loaders when
  • You're performing an action at application start-up.
  • You're establishing a one-time connection with an external system.
Don't use loaders ifYou want to perform an action continuously or at a set time pattern in the application. Use scheduled jobs instead, which is explained in an upcoming chapter.
Was this chapter helpful?
Edit this page