1 ---
2 sidebar_label: "Extend Customer"
3 tags:
4 - customer
5 - tutorial
6 - extend module
7 - server
8 ---
9
10 import { Prerequisites } from "docs-ui"
11
12 export const metadata = {
13 title: `Extend Customer Data Model`,
14 }
15
16 # {metadata.title}
17
18 In this documentation, you'll learn how to extend a data model of the Customer Module to add a custom property.
19
20 You'll create a `Custom` data model in a module. This data model will have a `custom_name` property, which is the property you want to add to the [Customer data model](/references/customer/models/Customer) defined in the Customer Module.
21
22 You'll then learn how to:
23
24 - Link the `Custom` data model to the `Customer` data model.
25 - Set the `custom_name` property when a customer is created or updated using Medusa's API routes.
26 - Retrieve the `custom_name` property with the customer's details, in custom or existing API routes.
27
28 <Note title="Tip">
29
30 Similar steps can be applied to the `CustomerAddress` data model.
31
32 </Note>
33
34 ## Step 1: Define Custom Data Model
35
36 Consider you have a Hello Module defined in the `/src/modules/hello` directory.
37
38 <Note title="Tip">
39
40 If you don't have a module, follow [this guide](!docs!/learn/fundamentals/modules) to create one.
41
42 </Note>
43
44 To add the `custom_name` property to the `Customer` data model, you'll create in the Hello Module a data model that has the `custom_name` property.
45
46 Create the file `src/modules/hello/models/custom.ts` with the following content:
47
48 ```ts title="src/modules/hello/models/custom.ts"
49 import { model } from "@medusajs/framework/utils"
50
51 export const Custom = model.define("custom", {
52 id: model.id().primaryKey(),
53 custom_name: model.text(),
54 })
55 ```
56
57 This creates a `Custom` data model that has the `id` and `custom_name` properties.
58
59 <Note title="Tip">
60
61 Learn more about data models in [this guide](!docs!/learn/fundamentals/modules#1-create-data-model).
62
63 </Note>
64
65 ---
66
67 ## Step 2: Define Link to Customer Data Model
68
69 Next, you'll define a module link between the `Custom` and `Customer` data model. A module link allows you to form a relation between two data models of separate modules while maintaining module isolation.
70
71 <Note title="Tip">
72
73 Learn more about module links in [this guide](!docs!/learn/fundamentals/module-links).
74
75 </Note>
76
77 Create the file `src/links/customer-custom.ts` with the following content:
78
79 ```ts title="src/links/customer-custom.ts"
80 import { defineLink } from "@medusajs/framework/utils"
81 import HelloModule from "../modules/hello"
82 import CustomerModule from "@medusajs/medusa/customer"
83
84 export default defineLink(
85 CustomerModule.linkable.customer,
86 HelloModule.linkable.custom
87 )
88 ```
89
90 This defines a link between the `Customer` and `Custom` data models. Using this link, you'll later query data across the modules, and link records of each data model.
91
92 ---
93
94 ## Step 3: Generate and Run Migrations
95
96 <Prerequisites
97 items={[
98 {
99 text: "Module must be registered in medusa-config.ts",
100 link: "!docs!/learn/fundamentals/modules#4-add-module-to-configurations"
101 }
102 ]}
103 />
104
105 To reflect the `Custom` data model in the database, generate a migration that defines the table to be created for it.
106
107 Run the following command in your Medusa project's root:
108
109 ```bash npx2yarn
110 npx medusa db:generate helloModuleService
111 ```
112
113 Where `helloModuleService` is your module's name.
114
115 Then, run the `db:migrate` command to run the migrations and create a table in the database for the link between the `Customer` and `Custom` data models:
116
117 ```bash npx2yarn
118 npx medusa db:migrate
119 ```
120
121 A table for the link is now created in the database. You can now retrieve and manage the link between records of the data models.
122
123 ---
124
125 ## Step 4: Consume customersCreated Workflow Hook
126
127 When a customer is created, you also want to create a `Custom` record and set the `custom_name` property, then create a link between the `Customer` and `Custom` records.
128
129 To do that, you'll consume the [customersCreated](/references/medusa-workflows/createCustomersWorkflow#customerscreated) hook of the [createCustomersWorkflow](/references/medusa-workflows/createCustomersWorkflow). This workflow is executed in the [Create Customer Admin API route](!api!/admin/customers/create-customer)
130
131 <Note title="Tip">
132
133 Learn more about workflow hooks in [this guide](!docs!/learn/fundamentals/workflows/workflow-hooks).
134
135 </Note>
136
137 The API route accepts in its request body an `additional_data` parameter. You can pass in it custom data, which is passed to the workflow hook handler.
138
139 ### Add custom_name to Additional Data Validation
140
141 To pass the `custom_name` in the `additional_data` parameter, you must add a validation rule that tells the Medusa application about this custom property.
142
143 Create the file `src/api/middlewares.ts` with the following content:
144
145 <Note>
146
147 As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`.
148
149 </Note>
150
151 ```ts title="src/api/middlewares.ts"
152 import { defineMiddlewares } from "@medusajs/framework/http"
153 import { z } from "@medusajs/framework/zod"
154
155 export default defineMiddlewares({
156 routes: [
157 {
158 method: "POST",
159 matcher: "/admin/customers",
160 additionalDataValidator: {
161 custom_name: z.string().optional(),
162 },
163 },
164 ],
165 })
166 ```
167
168 The `additional_data` parameter validation is customized using `defineMiddlewares`. In the routes middleware configuration object, the `additionalDataValidator` property accepts [Zod](https://zod.dev/) validation rules.
169
170 In the snippet above, you add a validation rule indicating that `custom_name` is a string that can be passed in the `additional_data` object.
171
172 <Note title="Tip">
173
174 Learn more about additional data validation in [this guide](!docs!/learn/fundamentals/api-routes/additional-data).
175
176 </Note>
177
178 ### Create Workflow to Create Custom Record
179
180 You'll now create a workflow that will be used in the hook handler.
181
182 This workflow will create a `Custom` record, then link it to the customer.
183
184 Start by creating the step that creates the `Custom` record. Create the file `src/workflows/create-custom-from-customer/steps/create-custom.ts` with the following content:
185
186 ```ts title="src/workflows/create-custom-from-customer/steps/create-custom.ts"
187 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
188 import HelloModuleService from "../../../modules/hello/service"
189 import { HELLO_MODULE } from "../../../modules/hello"
190
191 type CreateCustomStepInput = {
192 custom_name?: string
193 }
194
195 export const createCustomStep = createStep(
196 "create-custom",
197 async (data: CreateCustomStepInput, { container }) => {
198 if (!data.custom_name) {
199 return
200 }
201
202 const helloModuleService: HelloModuleService = container.resolve(
203 HELLO_MODULE
204 )
205
206 const custom = await helloModuleService.createCustoms(data)
207
208 return new StepResponse(custom, custom)
209 },
210 async (custom, { container }) => {
211 const helloModuleService: HelloModuleService = container.resolve(
212 HELLO_MODULE
213 )
214
215 await helloModuleService.deleteCustoms(custom.id)
216 }
217 )
218 ```
219
220 In the step, you resolve the Hello Module's main service and create a `Custom` record.
221
222 In the compensation function that undoes the step's actions in case of an error, you delete the created record.
223
224 <Note title="Tip">
225
226 Learn more about compensation functions in [this guide](!docs!/learn/fundamentals/workflows/compensation-function).
227
228 </Note>
229
230 Then, create the workflow at `src/workflows/create-custom-from-customer/index.ts` with the following content:
231
232 ```ts title="src/workflows/create-custom-from-customer/index.ts" collapsibleLines="1-7" expandButtonLabel="Show Imports"
233 import { createWorkflow, transform, when, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
234 import { CustomerDTO } from "@medusajs/framework/types"
235 import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
236 import { Modules } from "@medusajs/framework/utils"
237 import { HELLO_MODULE } from "../../modules/hello"
238 import { createCustomStep } from "./steps/create-custom"
239
240 export type CreateCustomFromCustomerWorkflowInput = {
241 customer: CustomerDTO
242 additional_data?: {
243 custom_name?: string
244 }
245 }
246
247 export const createCustomFromCustomerWorkflow = createWorkflow(
248 "create-custom-from-customer",
249 (input: CreateCustomFromCustomerWorkflowInput) => {
250 const customName = transform(
251 {
252 input,
253 },
254 (data) => data.input.additional_data.custom_name || ""
255 )
256
257 const custom = createCustomStep({
258 custom_name: customName,
259 })
260
261 when(({ custom }), ({ custom }) => custom !== undefined)
262 .then(() => {
263 createRemoteLinkStep([{
264 [Modules.CUSTOMER]: {
265 customer_id: input.customer.id,
266 },
267 [HELLO_MODULE]: {
268 custom_id: custom.id,
269 },
270 }])
271 })
272
273 return new WorkflowResponse({
274 custom,
275 })
276 }
277 )
278 ```
279
280 The workflow accepts as an input the created customer and the `additional_data` parameter passed in the request. This is the same input that the `customersCreated` hook accepts.
281
282 In the workflow, you:
283
284 1. Use `transform` to get the value of `custom_name` based on whether it's set in `additional_data`. Learn more about why you can't use conditional operators in a workflow without using `transform` in [this guide](!docs!/learn/fundamentals/workflows/conditions#why-if-conditions-arent-allowed-in-workflows).
285 2. Create the `Custom` record using the `createCustomStep`.
286 3. Use `when-then` to link the customer to the `Custom` record if it was created. Learn more about why you can't use if-then conditions in a workflow without using `when-then` in [this guide](!docs!/learn/fundamentals/workflows/conditions#why-if-conditions-arent-allowed-in-workflows).
287
288 You'll next execute the workflow in the hook handler.
289
290 ### Consume Workflow Hook
291
292 You can now consume the `customersCreated` hook, which is executed in the `createCustomersWorkflow` after the customer is created.
293
294 To consume the hook, create the file `src/workflow/hooks/user-created.ts` with the following content:
295
296 ```ts title="src/workflow/hooks/user-created.ts" collapsibleLines="1-6" expandButtonLabel="Show Imports"
297 import { createCustomersWorkflow } from "@medusajs/medusa/core-flows"
298 import {
299 createCustomFromCustomerWorkflow,
300 CreateCustomFromCustomerWorkflowInput,
301 } from "../create-custom-from-customer"
302
303 createCustomersWorkflow.hooks.customersCreated(
304 async ({ customers, additional_data }, { container }) => {
305 const workflow = createCustomFromCustomerWorkflow(container)
306
307 for (const customer of customers) {
308 await workflow.run({
309 input: {
310 customer,
311 additional_data,
312 } as CreateCustomFromCustomerWorkflowInput,
313 })
314 }
315 }
316 )
317 ```
318
319 The hook handler executes the `createCustomFromCustomerWorkflow`, passing it its input.
320
321 ### Test it Out
322
323 To test it out, send a `POST` request to `/admin/customers` to create a customer, passing `custom_name` in `additional_data`:
324
325 ```bash
326 curl -X POST 'localhost:9000/admin/customers' \
327 -H 'Content-Type: application/json' \
328 -H 'Authorization: Bearer {token}' \
329 --data-raw '{
330 "email": "customer@gmail.com",
331 "additional_data": {
332 "custom_name": "test"
333 }
334 }'
335 ```
336
337 Make sure to replace `{token}` with an admin user's JWT token. Learn how to retrieve it in the [API reference](!api!/admin#1-bearer-authorization-with-jwt-tokens).
338
339 The request will return the customer's details. You'll learn how to retrieve the `custom_name` property with the customer's details in the next section.
340
341 ---
342
343 ## Step 5: Retrieve custom_name with Customer Details
344
345 When you extend an existing data model through links, you also want to retrieve the custom properties with the data model.
346
347 ### Retrieve in API Routes using Query
348
349 You can also retrieve the `Custom` record linked to a customer in your code using [Query](!docs!/learn/fundamentals/query).
350
351 For example:
352
353 ```ts
354 const { data: [customer] } = await query.graph({
355 entity: "customer",
356 fields: ["*", "custom.*"],
357 filters: {
358 id: customer_id,
359 },
360 })
361 ```
362
363 You can use Query in a custom route to retrieve the customer with its linked `Custom` record.
364
365 Learn more about how to use Query in [this guide](!docs!/learn/fundamentals/query).
366
367 ### Retrieve in Store API Routes
368
369 The [Store Customer API routes](!api!/store/customers) only return the fields in their allowed fields, and `custom` isn't one of them, so Medusa removes it from the response without an error. To retrieve it, add it to the route's allowed fields in `src/api/middlewares.ts`:
370
371 ```ts title="src/api/middlewares.ts"
372 import { allowFields } from "@medusajs/framework/http"
373
374 export default defineMiddlewares({
375 routes: [
376 // ...
377 {
378 matcher: "/store/customers/me",
379 middlewares: [allowFields("custom")],
380 },
381 ],
382 })
383 ```
384
385 <Note>
386
387 `allowFields` is available since Medusa [v2.21.0](https://github.com/medusajs/medusa/releases/tag/v2.21.0). In earlier versions, write the middleware yourself, as explained in the [Allowed Fields](!docs!/learn/fundamentals/api-routes/allowed-fields#how-to-override-allowed-fields-of-medusas-api-routes) documentation.
388
389 </Note>
390
391 You can then pass `+custom.*` in the `fields` query parameter of the Store Customer API routes.
392
393 <Note title="Important">
394
395 The middleware must be global, so don't set a `method` property in the route object. Medusa runs a middleware scoped to a method after it validates the `fields` query parameter, so it has no effect.
396
397 </Note>
398
399 Learn more in the [Allowed Fields](!docs!/learn/fundamentals/api-routes/allowed-fields) documentation.
400
401 ---
402
403 ## Step 6: Consume customersUpdated Workflow Hook
404
405 Similar to the `customersCreated` hook, you'll consume the [customersUpdated](/references/medusa-workflows/updateCustomersWorkflow#customersUpdated) hook of the [updateCustomersWorkflow](/references/medusa-workflows/updateCustomersWorkflow) to update `custom_name` when the customer is updated.
406
407 The `updateCustomersWorkflow` is executed by the [Update Customer API route](!api!/admin/customers/update-a-customer), which accepts the `additional_data` parameter to pass custom data to the hook.
408
409 ### Add custom_name to Additional Data Validation
410
411 To allow passing `custom_name` in the `additional_data` parameter of the update customer route, add in `src/api/middlewares.ts` a new route middleware configuration object:
412
413 <Note>
414
415 As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`.
416
417 </Note>
418
419 ```ts title="src/api/middlewares.ts"
420 import { defineMiddlewares } from "@medusajs/framework/http"
421 import { z } from "@medusajs/framework/zod"
422
423 export default defineMiddlewares({
424 routes: [
425 // ...
426 {
427 method: "POST",
428 matcher: "/admin/customers/:id",
429 additionalDataValidator: {
430 custom_name: z.string().nullish(),
431 },
432 },
433 ],
434 })
435 ```
436
437 The validation schema is the similar to that of the Create Customer API route, except you can pass a `null` value for `custom_name` to remove or unset the `custom_name`'s value.
438
439 ### Create Workflow to Update Custom Record
440
441 Next, you'll create a workflow that creates, updates, or deletes `Custom` records based on the provided `additional_data` parameter:
442
443 1. If `additional_data.custom_name` is set and it's `null`, the `Custom` record linked to the customer is deleted.
444 2. If `additional_data.custom_name` is set and the customer doesn't have a linked `Custom` record, a new record is created and linked to the customer.
445 3. If `additional_data.custom_name` is set and the customer has a linked `Custom` record, the `custom_name` property of the `Custom` record is updated.
446
447 Start by creating the step that updates a `Custom` record. Create the file `src/workflows/update-custom-from-customer/steps/update-custom.ts` with the following content:
448
449 ```ts title="src/workflows/update-custom-from-customer/steps/update-custom.ts"
450 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
451 import { HELLO_MODULE } from "../../../modules/hello"
452 import HelloModuleService from "../../../modules/hello/service"
453
454 type UpdateCustomStepInput = {
455 id: string
456 custom_name: string
457 }
458
459 export const updateCustomStep = createStep(
460 "update-custom",
461 async ({ id, custom_name }: UpdateCustomStepInput, { container }) => {
462 const helloModuleService: HelloModuleService = container.resolve(
463 HELLO_MODULE
464 )
465
466 const prevData = await helloModuleService.retrieveCustom(id)
467
468 const custom = await helloModuleService.updateCustoms({
469 id,
470 custom_name,
471 })
472
473 return new StepResponse(custom, prevData)
474 },
475 async (prevData, { container }) => {
476 const helloModuleService: HelloModuleService = container.resolve(
477 HELLO_MODULE
478 )
479
480 await helloModuleService.updateCustoms(prevData)
481 }
482 )
483 ```
484
485 In this step, you update a `Custom` record. In the compensation function, you revert the update.
486
487 Next, you'll create the step that deletes a `Custom` record. Create the file `src/workflows/update-custom-from-customer/steps/delete-custom.ts` with the following content:
488
489 ```ts title="src/workflows/update-custom-from-customer/steps/delete-custom.ts" collapsibleLines="1-6" expandButtonLabel="Show Imports"
490 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
491 import { Custom } from "../../../modules/hello/models/custom"
492 import { InferTypeOf } from "@medusajs/framework/types"
493 import HelloModuleService from "../../../modules/hello/service"
494 import { HELLO_MODULE } from "../../../modules/hello"
495
496 type DeleteCustomStepInput = {
497 custom: InferTypeOf<typeof Custom>
498 }
499
500 export const deleteCustomStep = createStep(
501 "delete-custom",
502 async ({ custom }: DeleteCustomStepInput, { container }) => {
503 const helloModuleService: HelloModuleService = container.resolve(
504 HELLO_MODULE
505 )
506
507 await helloModuleService.deleteCustoms(custom.id)
508
509 return new StepResponse(custom, custom)
510 },
511 async (custom, { container }) => {
512 const helloModuleService: HelloModuleService = container.resolve(
513 HELLO_MODULE
514 )
515
516 await helloModuleService.createCustoms(custom)
517 }
518 )
519 ```
520
521 In this step, you delete a `Custom` record. In the compensation function, you create it again.
522
523 Finally, you'll create the workflow. Create the file `src/workflows/update-custom-from-customer/index.ts` with the following content:
524
525 ```ts title="src/workflows/update-custom-from-customer/index.ts" collapsibleLines="1-9" expandButtonLabel="Show Imports"
526 import { CustomerDTO } from "@medusajs/framework/types"
527 import { createWorkflow, when, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
528 import { createRemoteLinkStep, dismissRemoteLinkStep, useQueryGraphStep } from "@medusajs/medusa/core-flows"
529 import { createCustomStep } from "../create-custom-from-customer/steps/create-custom"
530 import { Modules } from "@medusajs/framework/utils"
531 import { HELLO_MODULE } from "../../modules/hello"
532 import { deleteCustomStep } from "./steps/delete-custom"
533 import { updateCustomStep } from "./steps/update-custom"
534
535 export type UpdateCustomFromCustomerStepInput = {
536 customer: CustomerDTO
537 additional_data?: {
538 custom_name?: string | null
539 }
540 }
541
542 export const updateCustomFromCustomerWorkflow = createWorkflow(
543 "update-custom-from-customer",
544 (input: UpdateCustomFromCustomerStepInput) => {
545 const { data: customers } = useQueryGraphStep({
546 entity: "customer",
547 fields: ["custom.*"],
548 filters: {
549 id: input.customer.id,
550 },
551 })
552
553 // TODO create, update, or delete Custom record
554 }
555 )
556 ```
557
558 The workflow accepts the same input as the `customersUpdated` workflow hook handler would.
559
560 In the workflow, you retrieve the customer's linked `Custom` record using Query.
561
562 Next, replace the `TODO` with the following:
563
564 ```ts title="src/workflows/update-custom-from-customer/index.ts"
565 const created = when(
566 "create-customer-custom-link",
567 {
568 input,
569 customers,
570 }, (data) =>
571 !data.customers[0].custom &&
572 data.input.additional_data?.custom_name?.length > 0
573 )
574 .then(() => {
575 const custom = createCustomStep({
576 custom_name: input.additional_data.custom_name,
577 })
578
579 createRemoteLinkStep([{
580 [Modules.CUSTOMER]: {
581 customer_id: input.customer.id,
582 },
583 [HELLO_MODULE]: {
584 custom_id: custom.id,
585 },
586 }])
587
588 return custom
589 })
590
591 // TODO update, or delete Custom record
592 ```
593
594 Using `when-then`, you check if the customer doesn't have a linked `Custom` record and the `custom_name` property is set. If so, you create a `Custom` record and link it to the customer.
595
596 To create the `Custom` record, you use the `createCustomStep` you created in an earlier section.
597
598 Next, replace the new `TODO` with the following:
599
600 ```ts title="src/workflows/update-custom-from-customer/index.ts"
601 const deleted = when(
602 "delete-customer-custom-link",
603 {
604 input,
605 customers,
606 }, (data) =>
607 data.customers[0].custom && (
608 data.input.additional_data?.custom_name === null ||
609 data.input.additional_data?.custom_name.length === 0
610 )
611 )
612 .then(() => {
613 deleteCustomStep({
614 custom: customers[0].custom,
615 })
616
617 dismissRemoteLinkStep({
618 [HELLO_MODULE]: {
619 custom_id: customers[0].custom.id,
620 },
621 })
622
623 return customers[0].custom.id
624 })
625
626 // TODO delete Custom record
627 ```
628
629 Using `when-then`, you check if the customer has a linked `Custom` record and `custom_name` is `null` or an empty string. If so, you delete the linked `Custom` record and dismiss its links.
630
631 Finally, replace the new `TODO` with the following:
632
633 ```ts title="src/workflows/update-custom-from-customer/index.ts"
634 const updated = when({
635 input,
636 customers,
637 }, (data) => data.customers[0].custom && data.input.additional_data?.custom_name?.length > 0)
638 .then(() => {
639 return updateCustomStep({
640 id: customers[0].custom.id,
641 custom_name: input.additional_data.custom_name,
642 })
643 })
644
645 return new WorkflowResponse({
646 created,
647 updated,
648 deleted,
649 })
650 ```
651
652 Using `when-then`, you check if the customer has a linked `Custom` record and `custom_name` is passed in the `additional_data`. If so, you update the linked `Custom` record.
653
654 You return in the workflow response the created, updated, and deleted `Custom` record.
655
656 ### Consume customersUpdated Workflow Hook
657
658 You can now consume the `customersUpdated` and execute the workflow you created.
659
660 Create the file `src/workflows/hooks/customer-updated.ts` with the following content:
661
662 ```ts title="src/workflows/hooks/customer-updated.ts"
663 import { updateCustomersWorkflow } from "@medusajs/medusa/core-flows"
664 import {
665 UpdateCustomFromCustomerStepInput,
666 updateCustomFromCustomerWorkflow,
667 } from "../update-custom-from-customer"
668
669 updateCustomersWorkflow.hooks.customersUpdated(
670 async ({ customers, additional_data }, { container }) => {
671 const workflow = updateCustomFromCustomerWorkflow(container)
672
673 for (const customer of customers) {
674 await workflow.run({
675 input: {
676 customer,
677 additional_data,
678 } as UpdateCustomFromCustomerStepInput,
679 })
680 }
681 }
682 )
683 ```
684
685 In the workflow hook handler, you execute the workflow, passing it the hook's input.
686
687 ### Test it Out
688
689 To test it out, send a `POST` request to `/admin/customers/:id` to update a customer, passing `custom_name` in `additional_data`:
690
691 ```bash
692 curl -X POST 'localhost:9000/admin/customers/{customer_id}' \
693 -H 'Content-Type: application/json' \
694 -H 'Authorization: Bearer {token}' \
695 --data '{
696 "additional_data": {
697 "custom_name": "test3"
698 }
699 }'
700 ```
701
702 Make sure to replace `{customer_id}` with the customer's ID, and `{token}` with the JWT token of an admin user.
703
704 The request will return the customer's details with the updated `custom` linked record.