1 import { Prerequisites } from "docs-ui"
2
3 export const metadata = {
4 title: `${pageNumber} Loaders`,
5 }
6
7 # {metadata.title}
8
9 In this chapter, you’ll learn about loaders and how to use them.
10
11 ## What is a Loader?
12
13 When building a commerce application, you'll often need to execute an action the first time the application starts. For example, if your application needs to connect to databases other than Medusa's PostgreSQL database, you might need to establish a connection on application startup.
14
15 In Medusa, you can execute an action when the application starts using a loader. A loader is a function exported by a [module](../page.mdx), which is a package of business logic for a single domain. When the Medusa application starts, it executes all loaders exported by configured modules.
16
17 Loaders are useful to register custom resources, such as database connections, in the [module's container](../container/page.mdx), which is similar to the [Medusa container](../../medusa-container/page.mdx) but includes only [resources available to the module](!resources!/medusa-container-resources#module-container-resources). Modules are isolated, so they can't access resources outside of them, such as a service in another module.
18
19 <Note title="Why are modules isolated?">
20
21 Medusa isolates modules to ensure that they're re-usable across applications, aren't tightly coupled to other resources, and don't have implications when integrated into the Medusa application. Learn more about why modules are isolated in [this chapter](../isolation/page.mdx), and check out [this reference for the list of resources in the module's container](!resources!/medusa-container-resources#module-container-resources).
22
23 </Note>
24
25 ---
26
27 ## How to Create a Loader?
28
29 ### 1. Implement Loader Function
30
31 You create a loader function in a TypeScript or JavaScript file under a module's `loaders` directory.
32
33 For example, consider you have a `hello` module, you can create a loader at `src/modules/hello/loaders/hello-world.ts` with the following content:
34
35 ![Example of loader file in the application's directory structure](https://res.cloudinary.com/dza7lstvk/image/upload/v1732865671/Medusa%20Book/loader-dir-overview_eg6vtu.jpg)
36
37 <Note title="Tip">
38
39 Learn how to create a module in [this chapter](../page.mdx).
40
41 </Note>
42
43 ```ts title="src/modules/hello/loaders/hello-world.ts"
44 import {
45 LoaderOptions,
46 } from "@medusajs/framework/types"
47 import {
48 ContainerRegistrationKeys,
49 } from "@medusajs/framework/utils"
50
51 export default async function helloWorldLoader({
52 container,
53 }: LoaderOptions) {
54 const logger = container.resolve(
55 ContainerRegistrationKeys.LOGGER
56 )
57
58 logger.info("[HELLO MODULE] Just started the Medusa application!")
59 }
60 ```
61
62 The loader file exports an async function, which is the function executed when the application loads.
63
64 The function receives an object parameter that has a `container` property, which is the module's container that you can use to resolve resources from. In this example, you resolve the Logger utility to log a message in the terminal.
65
66 <Note title="Tip">
67
68 Find the list of resources in the module's container in [this reference](!resources!/medusa-container-resources#module-container-resources).
69
70 </Note>
71
72 ### 2. Export Loader in Module Definition
73
74 After implementing the loader, you must export it in the module's definition in the `index.ts` file at the root of the module's directory. Otherwise, the Medusa application will not run it.
75
76 So, to export the loader you implemented above in the `hello` module, add the following to `src/modules/hello/index.ts`:
77
78 ```ts title="src/modules/hello/index.ts"
79 // other imports...
80 import helloWorldLoader from "./loaders/hello-world"
81
82 export default Module("hello", {
83 // ...
84 loaders: [helloWorldLoader],
85 })
86 ```
87
88 The second parameter of the `Module` function accepts a `loaders` property whose value is an array of loader functions. The Medusa application will execute these functions when it starts.
89
90 ### Test the Loader
91
92 Assuming your module is [added to Medusa's configuration](../page.mdx#4-add-module-to-medusas-configurations), you can test the loader by starting the Medusa application:
93
94 ```bash npm2yarn
95 npm run dev
96 ```
97
98 Then, you'll find the following message logged in the terminal:
99
100 ```plain
101 info: [HELLO MODULE] Just started the Medusa application!
102 ```
103
104 This indicates that the loader in the `hello` module ran and logged this message.
105
106 ---
107
108 ## When are Loaders Executed?
109
110 ### Loaders Executed on Application Startup
111
112 When you start the Medusa application, it executes the loaders of all modules in their registration order.
113
114 A loader is executed before the module's main service is instantiated. So, you can use loaders to register in the module's container resources that you want to use in the module's service. For example, you can register a database connection.
115
116 Loaders are also useful to only load a module if a certain condition is met. For example, if you try to connect to a database in a loader but the connection fails, you can throw an error in the loader to prevent the module from being loaded. This is useful if your module depends on an external service to work.
117
118 ### Loaders Executed with Migrations
119
120 Loaders are also executed when you run [migrations](../../data-models/write-migration/page.mdx). This can be useful if you need to run some task before the migrations, or you want to migrate some data to an integrated third-party system as part of the migration process.
121
122 ---
123
124 ## Avoid Heavy Operations in Loaders
125
126 Since loaders are executed when the Medusa application starts, heavy operations will increase the startup time of the application.
127
128 So, avoid operations that take a long time to complete, such as fetching a large amount of data from an external API or database, in loaders.
129
130 ### Alternative Solutions
131
132 Instead of performing heavy operations in loaders, consider one of the following solutions:
133
134 - Use a [scheduled job](../../scheduled-jobs/page.mdx) to perform the operation at specified intervals. This way, the operation is performed asynchronously and doesn't block the application startup.
135 - [Emit custom events](../../events-and-subscribers/emit-event/page.mdx) in an [API route](../../api-routes/page.mdx), then handle the event in a [subscriber](../../events-and-subscribers/page.mdx) to perform the operation asynchronously. You can then send a request to the API route to trigger the operation when needed.
136
137 ---
138
139 ## Example: Register Custom MongoDB Connection
140
141 As mentioned in this chapter's introduction, loaders are most useful when you need to register a custom resource in the module's container to re-use it in other customizations in the module.
142
143 Consider your have a MongoDB module that allows you to perform operations on a MongoDB database.
144
145 <Prerequisites
146 items={[
147 {
148 text: "MongoDB database that you can connect to from a local machine.",
149 link: "https://www.mongodb.com"
150 },
151 {
152 text: "Install the MongoDB SDK in your Medusa application.",
153 link: "https://www.mongodb.com/docs/drivers/node/current/quick-start/download-and-install/#install-the-node.js-driver"
154 }
155 ]}
156 />
157
158 To connect to the database, you create the following loader in your module:
159
160 <Note>
161
162 As of [Medusa v2.11.0](https://github.com/medusajs/medusa/releases/tag/v2.11.0), Awilix dependencies are included in the `@medusajs/framework` package. If you're using an older version of Medusa, change the import statement to `awilix`.
163
164 </Note>
165
166 export const loaderHighlights = [
167 ["9", "ModuleOptions", "Define a type for expected options."],
168 ["17", "ModuleOptions", "Pass the option type as a type argument to `LoaderOptions`."],
169 ["35", "clientDb", "Create a client instance that connects to the specified database."],
170 ["41", "register", "Register custom resource in the container."],
171 ["42", `"mongoClient"`, "The resource's key in the container."],
172 ["43", "asValue(clientDb)", "The resource to register."]
173 ]
174
175 ```ts title="src/modules/mongo/loaders/connection.ts" highlights={loaderHighlights}
176 import { LoaderOptions } from "@medusajs/framework/types"
177 import { asValue } from "@medusajs/framework/awilix"
178 import { MongoClient } from "mongodb"
179 import {
180 ContainerRegistrationKeys,
181 MedusaError,
182 } from "@medusajs/framework/utils"
183
184 type ModuleOptions = {
185 connection_url?: string
186 db_name?: string
187 }
188
189 export default async function mongoConnectionLoader({
190 container,
191 options,
192 }: LoaderOptions<ModuleOptions>) {
193 if (!options.connection_url) {
194 throw new MedusaError(
195 MedusaError.Types.INVALID_ARGUMENT,
196 `[MONGO MDOULE]: connection_url option is required.`
197 )
198 }
199 if (!options.db_name) {
200 throw new MedusaError(
201 MedusaError.Types.INVALID_ARGUMENT,
202 `[MONGO MDOULE]: db_name option is required.`
203 )
204 }
205 const logger = container.resolve(
206 ContainerRegistrationKeys.LOGGER
207 )
208
209 try {
210 const clientDb = (
211 await (new MongoClient(options.connection_url)).connect()
212 ).db(options.db_name)
213
214 logger.info("Connected to MongoDB")
215
216 container.register(
217 "mongoClient",
218 asValue(clientDb)
219 )
220 } catch (e) {
221 logger.error(
222 `[MONGO MDOULE]: An error occurred while connecting to MongoDB: ${e}`
223 )
224 }
225 }
226 ```
227
228 The loader function accepts in its object parameter an `options` property, which is the options passed to the module in Medusa's configurations. For example:
229
230 export const optionHighlights = [
231 ["6", "options", "The options to pass to the module."]
232 ]
233
234 ```ts title="medusa-config.ts" highlights={optionHighlights}
235 module.exports = defineConfig({
236 // ...
237 modules: [
238 {
239 resolve: "./src/modules/mongo",
240 options: {
241 connection_url: process.env.MONGO_CONNECTION_URL,
242 db_name: process.env.MONGO_DB_NAME,
243 },
244 },
245 ],
246 })
247 ```
248
249 Passing options is useful when your module needs information like connection URLs or API keys, as it ensures your module can be re-usable across applications. For the MongoDB Module, you expect two options:
250
251 - `connection_url`: the URL to connect to the MongoDB database.
252 - `db_name`: The name of the database to connect to.
253
254 In the loader, you check first that these options are set before proceeding. Then, you create an instance of the MongoDB client and connect to the database specified in the options.
255
256 After creating the client, you register it in the module's container using the container's `register` method. The method accepts two parameters:
257
258 1. The key to register the resource under, which in this case is `mongoClient`. You'll use this name later to resolve the client.
259 2. The resource to register in the container, which is the MongoDB client you created. However, you don't pass the resource as-is. Instead, you need to use an `asValue` function imported from the [`@medusajs/framework/awilix` package](https://github.com/jeffijoe/awilix), which is the package used to implement the container functionality in Medusa.
260
261 ### Use Custom Registered Resource in Module's Service
262
263 After registering the custom MongoDB client in the module's container, you can now resolve and use it in the module's service.
264
265 For example:
266
267 export const serviceHighlights = [
268 ["10", "mongoClient", "Resolve the MongoDB client from the container."],
269 ["11", "mongoClient_", "Set the MongoDB client as a class property."],
270 ["14", "createMovie", "Add a method that uses the MongoDB client to create a document."],
271 ["30", "deleteMovie", "Add a method that uses the MongoDB client to delete a document."]
272 ]
273
274 ```ts title="src/modules/mongo/service.ts"
275 import type { Db } from "mongodb"
276
277 type InjectedDependencies = {
278 mongoClient: Db
279 }
280
281 export default class MongoModuleService {
282 private mongoClient_: Db
283
284 constructor({ mongoClient }: InjectedDependencies) {
285 this.mongoClient_ = mongoClient
286 }
287
288 async createMovie({ title }: {
289 title: string
290 }) {
291 const moviesCol = this.mongoClient_.collection("movie")
292
293 const insertedMovie = await moviesCol.insertOne({
294 title,
295 })
296
297 const movie = await moviesCol.findOne({
298 _id: insertedMovie.insertedId,
299 })
300
301 return movie
302 }
303
304 async deleteMovie(id: string) {
305 const moviesCol = this.mongoClient_.collection("movie")
306
307 await moviesCol.deleteOne({
308 _id: {
309 equals: id,
310 },
311 })
312 }
313 }
314 ```
315
316 The service `MongoModuleService` resolves the `mongoClient` resource you registered in the loader and sets it as a class property. You then use it in the `createMovie` and `deleteMovie` methods, which create and delete a document in a `movie` collection in the MongoDB database, respectively.
317
318 Make sure to export the loader in the module's definition in the `index.ts` file at the root directory of the module:
319
320 ```ts title="src/modules/mongo/index.ts" highlights={[["9"]]}
321 import { Module } from "@medusajs/framework/utils"
322 import MongoModuleService from "./service"
323 import mongoConnectionLoader from "./loaders/connection"
324
325 export const MONGO_MODULE = "mongo"
326
327 export default Module(MONGO_MODULE, {
328 service: MongoModuleService,
329 loaders: [mongoConnectionLoader],
330 })
331 ```
332
333 ### Test it Out
334
335 You can test the connection out by starting the Medusa application. If it's successful, you'll see the following message logged in the terminal:
336
337 ```bash
338 info: Connected to MongoDB
339 ```
340
341 You can now resolve the MongoDB Module's main service in your customizations to perform operations on the MongoDB database.