3.8. 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.

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:

1export default 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:

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:

[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 if
  • You 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?