1 ---
2 sidebar_title: "Custom Item Price"
3 tags:
4 - cart
5 - pricing
6 - server
7 - tutorial
8 - product
9 products:
10 - cart
11 - pricing
12 - product
13 ---
14
15 import { Github, PlaySolid } from "@medusajs/icons"
16 import { Prerequisites, WorkflowDiagram } from "docs-ui"
17
18 export const ogImage = "https://res.cloudinary.com/dza7lstvk/image/upload/v1738682676/Medusa%20Resources/guide-custom-item-pricing_lrilmb.jpg"
19
20 export const metadata = {
21 title: `Implement Custom Line Item Pricing in Medusa`,
22 openGraph: {
23 images: [
24 {
25 url: ogImage,
26 width: 1600,
27 height: 836,
28 type: "image/jpeg"
29 }
30 ],
31 },
32 twitter: {
33 images: [
34 {
35 url: ogImage,
36 width: 1600,
37 height: 836,
38 type: "image/jpeg"
39 }
40 ]
41 }
42 }
43
44 # {metadata.title}
45
46 In this guide, you'll learn how to add line items with custom prices to a cart in Medusa.
47
48 When you install a Medusa application, you get a fully-fledged commerce platform with a Framework for customization. The Medusa application's commerce features are built around [Commerce Modules](../../../commerce-modules/page.mdx) which are available out-of-the-box. These features include managing carts and adding line items to them.
49
50 By default, you can add product variants to the cart, where the price of its associated line item is based on the product variant's price. However, you can build customizations to add line items with custom prices to the cart. This is useful when integrating an Enterprise Resource Planning (ERP), Product Information Management (PIM), or other third-party services that provide real-time prices for your products.
51
52 To showcase how to add line items with custom prices to the cart, this guide uses [GoldAPI.io](https://www.goldapi.io) as an example of a third-party system that you can integrate for real-time prices. You can follow the same approach for other third-party integrations that provide custom pricing.
53
54 You can follow this guide whether you're new to Medusa or an advanced Medusa developer.
55
56 ### Summary
57
58 This guide will teach you how to:
59
60 - Install and set up Medusa.
61 - Integrate the third-party service [GoldAPI.io](https://www.goldapi.io) that retrieves real-time prices for metals like Gold and Silver.
62 - Add an API route to add a product variant that has metals, such as a gold ring, to the cart with the real-time price retrieved from the third-party service.
63
64 ![Diagram showcasing overview of implementation for adding an item to cart from storefront.](https://res.cloudinary.com/dza7lstvk/image/upload/v1738920014/Medusa%20Resources/custom-line-item-3_zu3qh2.jpg)
65
66 <CardList items={[
67 {
68 href: "https://github.com/medusajs/examples/tree/main/custom-item-price",
69 title: "Custom Item Price Repository",
70 text: "Find the full code for this guide in this repository.",
71 icon: Github,
72 },
73 {
74 href: "https://res.cloudinary.com/dza7lstvk/raw/upload/v1738246728/OpenApi/Custom_Item_Price_gdfnl3.yaml",
75 title: "OpenApi Specs for Postman",
76 text: "Import this OpenApi Specs file into tools like Postman.",
77 icon: PlaySolid,
78 },
79 ]} />
80
81 ---
82
83 ## Step 1: Install a Medusa Application
84
85 <Prerequisites items={[
86 {
87 text: "Node.js v20.19.0+ or v22.12.0+",
88 link: "https://nodejs.org/en/download"
89 },
90 {
91 text: "Git CLI tool",
92 link: "https://git-scm.com/downloads"
93 },
94 {
95 text: "PostgreSQL",
96 link: "https://www.postgresql.org/download/"
97 }
98 ]} />
99
100 Start by installing the Medusa application on your machine with the following command:
101
102 ```bash npx2yarnExec
103 npx create-medusa-app@latest
104 ```
105
106 You'll first be asked for the project's name. You can also optionally choose to install the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx).
107
108 Afterwards, the installation process will start, which will install the Medusa application as a monorepository in a directory with your project's name. The backend is installed in the `apps/backend` directory. If you chose to install the Next.js Starter Storefront, it'll be in the `apps/storefront` directory.
109
110 Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form. Afterwards, you can log in with the new user and explore the dashboard.
111
112 <Note title="Ran into Errors">
113
114 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
115
116 </Note>
117
118 <Note>
119
120 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
121
122 </Note>
123
124 ---
125
126 ## Step 2: Integrate GoldAPI.io
127
128 <Prerequisites
129 items={[
130 {
131 text: "GoldAPI.io Account. You can create a free account.",
132 link: "https://www.goldapi.io"
133 }
134 ]}
135 />
136
137 To integrate third-party services into Medusa, you create a custom module. A module is a reusable package with functionalities related to a single feature or domain. Medusa integrates the module into your application without implications or side effects on your setup.
138
139 In this step, you'll create a Metal Price Module that uses the GoldAPI.io service to retrieve real-time prices for metals like Gold and Silver. You'll use this module later to retrieve the real-time price of a product variant based on the metals in it, and add it to the cart with that custom price.
140
141 <Note>
142
143 Learn more about modules in [this documentation](!docs!/learn/fundamentals/modules).
144
145 </Note>
146
147 ### Create Module Directory
148
149 A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/metal-prices`.
150
151 ![Diagram showcasing the module directory to create](https://res.cloudinary.com/dza7lstvk/image/upload/v1738247192/Medusa%20Resources/custom-item-price-1_q16evr.jpg)
152
153 ### Create Module's Service
154
155 You define a module's functionalities in a service. A service is a TypeScript or JavaScript class that the module exports. In the service's methods, you can connect to the database, which is useful if your module defines tables in the database, or connect to a third-party service.
156
157 In this section, you'll create the Metal Prices Module's service that connects to the GoldAPI.io service to retrieve real-time prices for metals.
158
159 Start by creating the file `src/modules/metal-prices/service.ts` with the following content:
160
161 ![Diagram showcasing the service file to create](https://res.cloudinary.com/dza7lstvk/image/upload/v1738247303/Medusa%20Resources/custom-item-price-2_eaefis.jpg)
162
163 ```ts title="src/modules/metal-prices/service.ts"
164 type Options = {
165 accessToken: string
166 sandbox?: boolean
167 }
168
169 export default class MetalPricesModuleService {
170 protected options_: Options
171
172 constructor({}, options: Options) {
173 this.options_ = options
174 }
175 }
176 ```
177
178 A module can accept options that are passed to its service. You define an `Options` type that indicates the options the module accepts. It accepts two options:
179
180 - `accessToken`: The access token for the GoldAPI.io service.
181 - `sandbox`: A boolean that indicates whether to simulate sending requests to the GoldAPI.io service. This is useful when running in a test environment.
182
183 The service's constructor receives the module's options as a second parameter. You store the options in the service's `options_` property.
184
185 <Note title="What is the first parameter in the constructor?">
186
187 A module has a container of Medusa Framework tools and local resources in the module that you can access in the service constructor's first parameter. Learn more in [this documentation](!docs!/learn/fundamentals/modules/container).
188
189 </Note>
190
191 #### Add Method to Retrieve Metal Prices
192
193 Next, you'll add the method to retrieve the metal prices from the third-party service.
194
195 First, add the following types at the beginning of `src/modules/metal-prices/service.ts`:
196
197 ```ts title="src/modules/metal-prices/service.ts"
198 export enum MetalSymbols {
199 Gold = "XAU",
200 Silver = "XAG",
201 Platinum = "XPT",
202 Palladium = "XPD"
203 }
204
205 export type PriceResponse = {
206 metal: MetalSymbols
207 currency: string
208 exchange: string
209 symbol: string
210 price: number
211 [key: string]: unknown
212 }
213
214 ```
215
216 The `MetalSymbols` enum defines the symbols for metals like Gold, Silver, Platinum, and Palladium. The `PriceResponse` type defines the structure of the response from the GoldAPI.io's endpoint.
217
218 Next, add the method `getMetalPrices` to the `MetalPricesModuleService` class:
219
220 ```ts title="src/modules/metal-prices/service.ts"
221 import { MedusaError } from "@medusajs/framework/utils"
222
223 // ...
224
225 export default class MetalPricesModuleService {
226 // ...
227 async getMetalPrice(
228 symbol: MetalSymbols,
229 currency: string
230 ): Promise<PriceResponse> {
231 const upperCaseSymbol = symbol.toUpperCase()
232 const upperCaseCurrency = currency.toUpperCase()
233
234 return fetch(`https://www.goldapi.io/api/${upperCaseSymbol}/${upperCaseCurrency}`, {
235 headers: {
236 "x-access-token": this.options_.accessToken,
237 "Content-Type": "application/json",
238 },
239 redirect: "follow",
240 }).then((response) => response.json())
241 .then((response) => {
242 if (response.error) {
243 throw new MedusaError(
244 MedusaError.Types.INVALID_DATA,
245 response.error
246 )
247 }
248
249 return response
250 })
251 }
252 }
253 ```
254
255 The `getMetalPrice` method accepts the metal symbol and currency as parameters. You send a request to GoldAPI.io's `/api/{symbol}/{currency}` endpoint to retrieve the metal's price, also passing the access token in the request's headers.
256
257 If the response contains an error, you throw a `MedusaError` with the error message. Otherwise, you return the response, which is of type `PriceResponse`.
258
259 #### Add Helper Methods
260
261 You'll also add two helper methods to the `MetalPricesModuleService`. The first one is `getMetalSymbols` that returns the metal symbols as an array of strings:
262
263 ```ts title="src/modules/metal-prices/service.ts"
264 export default class MetalPricesModuleService {
265 // ...
266 async getMetalSymbols(): Promise<string[]> {
267 return Object.values(MetalSymbols)
268 }
269 }
270 ```
271
272 The second is `getMetalSymbol` that receives a name like `gold` and returns the corresponding metal symbol:
273
274 ```ts title="src/modules/metal-prices/service.ts"
275 export default class MetalPricesModuleService {
276 // ...
277 async getMetalSymbol(name: string): Promise<MetalSymbols | undefined> {
278 const formattedName = name.charAt(0).toUpperCase() + name.slice(1).toLowerCase()
279 return MetalSymbols[formattedName as keyof typeof MetalSymbols]
280 }
281 }
282 ```
283
284 You'll use these methods in later steps.
285
286 ### Export Module Definition
287
288 The final piece to a module is its definition, which you export in an `index.ts` file at its root directory. This definition tells Medusa the name of the module and its service.
289
290 So, create the file `src/modules/metal-prices/index.ts` with the following content:
291
292 ![The directory structure of the Metal Prices Module after adding the definition file.](https://res.cloudinary.com/dza7lstvk/image/upload/v1738248049/Medusa%20Resources/custom-item-price-3_imtbuw.jpg)
293
294 ```ts title="src/modules/metal-prices/index.ts"
295 import { Module } from "@medusajs/framework/utils"
296 import MetalPricesModuleService from "./service"
297
298 export const METAL_PRICES_MODULE = "metal_prices"
299
300 export default Module(METAL_PRICES_MODULE, {
301 service: MetalPricesModuleService,
302 })
303 ```
304
305 You use the `Module` function from the Modules SDK to create the module's definition. It accepts two parameters:
306
307 1. The module's name, which is `metal-prices`.
308 2. An object with a required property `service` indicating the module's service.
309
310 ### Add Module to Medusa's Configurations
311
312 Once you finish building the module, add it to Medusa's configurations to start using it.
313
314 In `medusa-config.ts`, add a `modules` property and pass an array with your custom module:
315
316 ```ts title="medusa-config.ts"
317 module.exports = defineConfig({
318 // ...
319 modules: [
320 {
321 resolve: "./src/modules/metal-prices",
322 options: {
323 accessToken: process.env.GOLD_API_TOKEN,
324 sandbox: process.env.GOLD_API_SANDBOX === "true",
325 },
326 },
327 ],
328 })
329 ```
330
331 Each object in the `modules` array has a `resolve` property, whose value is either a path to the module's directory, or an `npm` package’s name.
332
333 The object also has an `options` property that accepts the module's options. You set the `accessToken` and `sandbox` options based on environment variables.
334
335 You'll find the access token at the top of your GoldAPI.io dashboard.
336
337 ![The access token is below the "API Token" header of your GoldAPI.io dashboard.](https://res.cloudinary.com/dza7lstvk/image/upload/v1738248335/Medusa%20Resources/Screenshot_2025-01-30_at_4.44.07_PM_xht3j4.png)
338
339 Set the access token as an environment variable in `.env`:
340
341 ```bash
342 GOLD_API_TOKEN=
343 ```
344
345 You'll start using the module in the next steps.
346
347 ---
348
349 ## Step 3: Add Custom Item to Cart Workflow
350
351 In this section, you'll implement the logic to retrieve the real-time price of a variant based on the metals in it, then add the variant to the cart with the custom price. You'll implement this logic in a workflow.
352
353 A workflow is a series of queries and actions, called steps, that complete a task. You construct a workflow like you construct a function, but it's a special function that allows you to track its executions' progress, define roll-back logic, and configure other advanced features. Then, you execute the workflow from other customizations, such as in an endpoint.
354
355 <Note>
356
357 Learn more about workflows in [this documentation](!docs!/learn/fundamentals/workflows)
358
359 </Note>
360
361 The workflow you'll implement in this section has the following steps:
362
363 <WorkflowDiagram
364 workflow={{
365 name: "addCustomToCartWorkflow",
366 steps: [
367 {
368 type: "step",
369 name: "useQueryGraphStep (Retrieve Cart)",
370 description: "Retrieve the cart's ID and currency using Query.",
371 depth: 1,
372 link: "/references/helper-steps/useQueryGraphStep"
373 },
374 {
375 type: "step",
376 name: "useQueryGraphStep (Retrieve Variant)",
377 description: "Retrieve the variant's details using Query",
378 depth: 2,
379 link: "/references/helper-steps/useQueryGraphStep"
380 },
381 {
382 type: "step",
383 name: "getVariantMetalPricesStep",
384 description: "Retrieve the variant's price using the third-party service.",
385 depth: 3,
386 link: "#getvariantmetalpricesstep"
387 },
388 {
389 type: "step",
390 name: "acquireLockStep",
391 description: "Acquire a lock on the cart to prevent concurrent modifications.",
392 depth: 4,
393 link: "/references/medusa-workflows/steps/acquireLockStep",
394 },
395 {
396 type: "step",
397 name: "addToCartWorkflow",
398 description: "Add the item with the custom price to the cart.",
399 depth: 5,
400 link: "/references/medusa-workflows/addToCartWorkflow"
401 },
402 {
403 type: "step",
404 name: "useQueryGraphStep (Retrieve Cart)",
405 description: "Retrieve the updated cart's details using Query.",
406 depth: 6,
407 link: "/references/helper-steps/useQueryGraphStep"
408 },
409 {
410 type: "step",
411 name: "releaseLockStep",
412 description: "Release the lock on the cart.",
413 depth: 7,
414 link: "/references/medusa-workflows/steps/releaseLockStep",
415 }
416 ]
417 }}
418 hideLegend
419 />
420
421 You'll only implement the `getVariantMetalPricesStep`. Medusa provides the other steps out-of-the-box.
422
423 ### getVariantMetalPricesStep
424
425 The `getVariantMetalPricesStep` will retrieve the real-time metal price of a variant received as an input.
426
427 To create the step, create the file `src/workflows/steps/get-variant-metal-prices.ts` with the following content:
428
429 ![The directory structure after adding the step file.](https://res.cloudinary.com/dza7lstvk/image/upload/v1738249036/Medusa%20Resources/custom-item-price-4_kumzdc.jpg)
430
431 ```ts title="src/workflows/steps/get-variant-metal-prices.ts"
432 import { createStep } from "@medusajs/framework/workflows-sdk"
433 import { ProductVariantDTO } from "@medusajs/framework/types"
434 import { METAL_PRICES_MODULE } from "../../modules/metal-prices"
435 import MetalPricesModuleService from "../../modules/metal-prices/service"
436
437 export type GetVariantMetalPricesStepInput = {
438 variant: ProductVariantDTO & {
439 calculated_price?: {
440 calculated_amount: number
441 }
442 }
443 currencyCode: string
444 quantity?: number
445 }
446
447 export const getVariantMetalPricesStep = createStep(
448 "get-variant-metal-prices",
449 async ({
450 variant,
451 currencyCode,
452 quantity = 1,
453 }: GetVariantMetalPricesStepInput, { container }) => {
454 const metalPricesModuleService: MetalPricesModuleService =
455 container.resolve(METAL_PRICES_MODULE)
456
457 // TODO
458 }
459 )
460 ```
461
462 You create a step with `createStep` from the Workflows SDK. It accepts two parameters:
463
464 1. The step's unique name, which is `get-variant-metal-prices`.
465 2. An async function that receives two parameters:
466 - An input object with the variant, currency code, and quantity. The variant has a `calculated_price` property that holds the variant's fixed price in the Medusa application. This is useful when you want to add a fixed price to the real-time custom price, such as handling fees.
467 - The [Medusa container](!docs!/learn/fundamentals/medusa-container), which is a registry of Framework and commerce tools that you can access in the step.
468
469 In the step function, so far you only resolve the Metal Prices Module's service from the Medusa container.
470
471 Next, you'll validate that the specified variant can have its price calculated. Add the following import at the top of the file:
472
473 ```ts title="src/workflows/steps/get-variant-metal-prices.ts"
474 import { MedusaError } from "@medusajs/framework/utils"
475 ```
476
477 And replace the `TODO` in the step function with the following:
478
479 ```ts title="src/workflows/steps/get-variant-metal-prices.ts"
480 const variantMetal = variant.options.find(
481 (option) => option.option?.title === "Metal"
482 )?.value
483 const metalSymbol = await metalPricesModuleService
484 .getMetalSymbol(variantMetal || "")
485
486 if (!metalSymbol) {
487 throw new MedusaError(
488 MedusaError.Types.INVALID_DATA,
489 "Variant doesn't have metal. Make sure the variant's SKU matches a metal symbol."
490 )
491 }
492
493 if (!variant.weight) {
494 throw new MedusaError(
495 MedusaError.Types.INVALID_DATA,
496 "Variant doesn't have weight. Make sure the variant has weight to calculate its price."
497 )
498 }
499
500 // TODO retrieve custom price
501 ```
502
503 In the code above, you first retrieve the metal option's value from the variant's options, assuming that a variant has metals if it has a `Metal` option. Then, you retrieve the metal symbol of the option's value using the `getMetalSymbol` method of the Metal Prices Module's service.
504
505 If the variant doesn't have a metal in its options, the option's value is not valid, or the variant doesn't have a weight, you throw an error. The weight is necessary to calculate the price based on the metal's price per weight.
506
507 Next, you'll retrieve the real-time price of the metal using the third-party service. Replace the `TODO` with the following:
508
509 ```ts title="src/workflows/steps/get-variant-metal-prices.ts"
510 let price = variant.calculated_price?.calculated_amount || 0
511 const weight = variant.weight
512 const { price: metalPrice } = await metalPricesModuleService.getMetalPrice(
513 metalSymbol as MetalSymbols, currencyCode
514 )
515 price += (metalPrice * weight * quantity)
516
517 return new StepResponse(price)
518 ```
519
520 In the code above, you first set the price to the variant's fixed price, if it has one. Then, you retrieve the metal's price using the `getMetalPrice` method of the Metal Prices Module's service.
521
522 Finally, you calculate the price by multiplying the metal's price by the variant's weight and the quantity to add to the cart, then add the fixed price to it.
523
524 Every step must return a `StepResponse` instance. The `StepResponse` constructor accepts the step's output as a parameter, which in this case is the variant's price.
525
526 ### Create addCustomToCartWorkflow
527
528 Now that you have the `getVariantMetalPricesStep`, you can create the workflow that adds the item with custom pricing to the cart.
529
530 Create the file `src/workflows/add-custom-to-cart.ts` with the following content:
531
532 ![The directory structure after adding the workflow file.](https://res.cloudinary.com/dza7lstvk/image/upload/v1738251380/Medusa%20Resources/custom-item-price-5_zorahv.jpg)
533
534 export const workflowHighlights = [
535 ["17", "useQueryGraphStep", "Retrieve the cart's details."],
536 ["26", "useQueryGraphStep", "Retrieve the variant's details."],
537 ]
538
539 ```ts title="src/workflows/add-custom-to-cart.ts" highlights={workflowHighlights}
540 import { createWorkflow } from "@medusajs/framework/workflows-sdk"
541 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
542 import { QueryContext } from "@medusajs/framework/utils"
543
544 type AddCustomToCartWorkflowInput = {
545 cart_id: string
546 item: {
547 variant_id: string
548 quantity: number
549 metadata?: Record<string, unknown> | null
550 }
551 }
552
553 export const addCustomToCartWorkflow = createWorkflow(
554 "add-custom-to-cart",
555 ({ cart_id, item }: AddCustomToCartWorkflowInput) => {
556 const { data: carts } = useQueryGraphStep({
557 entity: "cart",
558 filters: { id: cart_id },
559 fields: ["id", "currency_code"],
560 options: {
561 throwIfKeyNotFound: true,
562 },
563 })
564
565 const { data: variants } = useQueryGraphStep({
566 entity: "variant",
567 fields: [
568 "*",
569 "options.*",
570 "options.option.*",
571 "calculated_price.*",
572 ],
573 filters: {
574 id: item.variant_id,
575 },
576 options: {
577 throwIfKeyNotFound: true,
578 },
579 context: {
580 calculated_price: QueryContext({
581 currency_code: carts[0].currency_code,
582 }),
583 },
584 }).config({ name: "retrieve-variant" })
585
586 // TODO add more steps
587 }
588 )
589 ```
590
591 You create a workflow with `createWorkflow` from the Workflows SDK. It accepts two parameters:
592
593 1. The workflow's unique name, which is `add-custom-to-cart`.
594 2. A function that receives an input object with the cart's ID and the item to add to the cart. The item has the variant's ID, quantity, and optional metadata.
595
596 In the function, you first retrieve the cart's details using the `useQueryGraphStep` helper step. This step uses [Query](!docs!/learn/fundamentals/query) which is a Modules SDK tool that retrieves data across modules. You use it to retrieve the cart's ID and currency code.
597
598 You also retrieve the variant's details using the `useQueryGraphStep` helper step. You pass the variant's ID to the step's filters and specify the fields to retrieve. To retrieve the variant's price based on the cart's context, you pass the cart's currency code to the `calculated_price` context.
599
600 Next, you'll retrieve the variant's real-time price using the `getVariantMetalPricesStep` you created earlier. First, add the following import:
601
602 ```ts title="src/workflows/add-custom-to-cart.ts"
603 import {
604 getVariantMetalPricesStep,
605 GetVariantMetalPricesStepInput,
606 } from "./steps/get-variant-metal-prices"
607 ```
608
609 Then, replace the `TODO` in the workflow with the following:
610
611 ```ts title="src/workflows/add-custom-to-cart.ts"
612 const price = getVariantMetalPricesStep({
613 variant: variants[0],
614 currencyCode: carts[0].currency_code,
615 quantity: item.quantity,
616 } as unknown as GetVariantMetalPricesStepInput)
617
618 // TODO add item with custom price to cart
619 ```
620
621 You execute the `getVariantMetalPricesStep` passing it the variant's details, the cart's currency code, and the quantity of the item to add to the cart. The step returns the variant's custom price.
622
623 Next, you'll add the item with the custom price to the cart. First, add the following imports at the top of the file:
624
625 ```ts title="src/workflows/add-custom-to-cart.ts"
626 import { transform } from "@medusajs/framework/workflows-sdk"
627 import {
628 acquireLockStep,
629 addToCartWorkflow,
630 } from "@medusajs/medusa/core-flows"
631 ```
632
633 Then, replace the `TODO` in the workflow with the following:
634
635 ```ts title="src/workflows/add-custom-to-cart.ts"
636 const itemToAdd = transform({
637 item,
638 price,
639 }, (data) => {
640 return [{
641 ...data.item,
642 unit_price: data.price,
643 }]
644 })
645
646 acquireLockStep({
647 key: cart_id,
648 timeout: 2,
649 ttl: 10,
650 })
651
652 addToCartWorkflow.runAsStep({
653 input: {
654 items: itemToAdd,
655 cart_id,
656 },
657 })
658
659 // TODO retrieve and return cart
660 ```
661
662 You prepare the item to add to the cart using `transform` from the Workflows SDK. It allows you to manipulate and create variables in a workflow.
663
664 After that, you use Medusa's `acquireLockStep` to acquire a lock on the cart, and `addToCartWorkflow` to add the item with the custom price to the cart.
665
666 <Note title="Tip">
667
668 A workflow's constructor function has some constraints in implementation, which is why you need to use `transform` for variable manipulation. Learn more about these constraints in [this documentation](!docs!/learn/fundamentals/workflows/constructor-constraints).
669
670 </Note>
671
672 Lastly, you'll retrieve the cart's details again and return them. Add the following import at the beginning of the file:
673
674 ```ts title="src/workflows/add-custom-to-cart.ts"
675 import { WorkflowResponse } from "@medusajs/framework/workflows-sdk"
676 import {
677 releaseLockStep,
678 } from "@medusajs/medusa/core-flows"
679 ```
680
681 And replace the last `TODO` in the workflow with the following:
682
683 ```ts title="src/workflows/add-custom-to-cart.ts"
684 const { data: updatedCarts } = useQueryGraphStep({
685 entity: "cart",
686 filters: { id: cart_id },
687 fields: ["id", "items.*"],
688 }).config({ name: "refetch-cart" })
689
690 releaseLockStep({
691 key: cart_id,
692 })
693
694 return new WorkflowResponse({
695 cart: updatedCarts[0],
696 })
697 ```
698
699 In the code above, you retrieve the updated cart's details using the `useQueryGraphStep` helper step. Then, you release the lock on the cart with the `releaseLockStep`.
700
701 To return data from the workflow, you create and return a `WorkflowResponse` instance. It accepts as a parameter the data to return, which is the updated cart.
702
703 In the next step, you'll use the workflow in a custom route to add an item with a custom price to the cart.
704
705 ---
706
707 ## Step 4: Create Add Custom Item to Cart API Route
708
709 Now that you've implemented the logic to add an item with a custom price to the cart, you'll expose this functionality in an API route.
710
711 An API Route is an endpoint that exposes commerce features to external applications and clients, such as storefronts. You'll create an API route at the path `/store/carts/:id/line-items-metals` that executes the workflow from the previous step to add a product variant with custom price to the cart.
712
713 <Note>
714
715 Learn more about API routes in [this documentation](!docs!/learn/fundamentals/api-routes).
716
717 </Note>
718
719 ### Create API Route
720
721 An API route is created in a `route.ts` file under a sub-directory of the `src/api` directory.
722
723 The path of the API route is the file's path relative to `src/api`. So, to create the `/store/carts/:id/line-items-metals` API route, create the file `src/api/store/carts/[id]/line-items-metals/route.ts` with the following content:
724
725 ![The directory structure after adding the API route file.](https://res.cloudinary.com/dza7lstvk/image/upload/v1738252712/Medusa%20Resources/custom-item-price-6_deecbu.jpg)
726
727 ```ts title="src/api/store/carts/[id]/line-items-metals/route.ts"
728 import { MedusaRequest, MedusaResponse } from "@medusajs/framework"
729 import { HttpTypes } from "@medusajs/framework/types"
730 import { addCustomToCartWorkflow } from "../../../../../workflows/add-custom-to-cart"
731
732 export const POST = async (
733 req: MedusaRequest<HttpTypes.StoreAddCartLineItem>,
734 res: MedusaResponse
735 ) => {
736 const { id } = req.params
737 const item = req.validatedBody
738
739 const { result } = await addCustomToCartWorkflow(req.scope)
740 .run({
741 input: {
742 cart_id: id,
743 item,
744 },
745 })
746
747 res.status(200).json({ cart: result.cart })
748 }
749 ```
750
751 Since you export a `POST` function in this file, you're exposing a `POST` API route at `/store/carts/:id/line-items-metals`. The route handler function accepts two parameters:
752
753 1. A request object with details and context on the request, such as path and body parameters.
754 2. A response object to manipulate and send the response.
755
756 In the function, you retrieve the cart's ID from the path parameter, and the item's details from the request body. This API route will accept the same request body parameters as Medusa's [Add Item to Cart API Route](!api!/store/carts/add-line-item).
757
758 Then, you execute the `addCustomToCartWorkflow` by invoking it, passing it the Medusa container, which is available in the request's `scope` property, then executing its `run` method. You pass the workflow's input object with the cart's ID and the item to add to the cart.
759
760 Finally, you return a response with the updated cart's details.
761
762 ### Add Request Body Validation Middleware
763
764 To ensure that the request body contains the required parameters, you'll add a middleware that validates the incoming request's body based on a defined schema.
765
766 A middleware is a function executed before the API route when a request is sent to it. You define middlewares in Medusa in the `src/api/middlewares.ts` directory.
767
768 <Note>
769
770 Learn more about middlewares in [this documentation](!docs!/learn/fundamentals/api-routes/middlewares).
771
772 </Note>
773
774 To add a validation middleware to the custom API route, create the file `src/api/middlewares.ts` with the following content:
775
776 ![The directory structure after adding the middleware file.](https://res.cloudinary.com/dza7lstvk/image/upload/v1738253099/Medusa%20Resources/custom-item-price-7_l7iw2a.jpg)
777
778 ```ts title="src/api/middlewares.ts"
779 import {
780 defineMiddlewares,
781 validateAndTransformBody,
782 } from "@medusajs/framework/http"
783 import {
784 StoreAddCartLineItem,
785 } from "@medusajs/medusa/api/store/carts/validators"
786
787 export default defineMiddlewares({
788 routes: [
789 {
790 matcher: "/store/carts/:id/line-items-metals",
791 method: "POST",
792 middlewares: [
793 validateAndTransformBody(
794 StoreAddCartLineItem
795 ),
796 ],
797 },
798 ],
799 })
800 ```
801
802 In this file, you export the middlewares definition using `defineMiddlewares` from the Medusa Framework. This function accepts an object having a `routes` property, which is an array of middleware configurations to apply on routes.
803
804 You pass in the `routes` array an object having the following properties:
805
806 - `matcher`: The route to apply the middleware on.
807 - `method`: The HTTP method to apply the middleware on for the specified API route.
808 - `middlewares`: An array of the middlewares to apply. You apply the `validateAndTransformBody` middleware, which validates the request body based on the `StoreAddCartLineItem` schema. This validation schema is the same schema used for Medusa's [Add Item to Cart API Route](!api!/store/carts/add-line-item).
809
810 Any request sent to the `/store/carts/:id/line-items-metals` API route will now fail if it doesn't have the required parameters.
811
812 <Note>
813
814 Learn more about API route validation in [this documentation](!docs!/learn/fundamentals/api-routes/validation).
815
816 </Note>
817
818 ### Prepare to Test API Route
819
820 Before you test the API route, you'll prepare and retrieve the necessary data to add a product variant with a custom price to the cart.
821
822 #### Create Product with Metal Variant
823
824 You'll first create a product that has a `Metal` option, and variant(s) with values for this option.
825
826 Start the Medusa application with the following command:
827
828 ```bash npm2yarn
829 npm run dev
830 ```
831
832 Then, open the Medusa Admin dashboard at `localhost:9000/app` and log in with the email and password you created when you installed the Medusa application in the first step.
833
834 Once you log in, click on Products in the sidebar, then click the Create button at the top right.
835
836 ![Click on Products in the sidebar at the left, then click on the Create button at the top right of the content](https://res.cloudinary.com/dza7lstvk/image/upload/v1738253415/Medusa%20Resources/Screenshot_2025-01-30_at_6.09.36_PM_ee0jr2.png)
837
838 Then, in the Create Product form:
839
840 1. Enter a name for the product, and optionally enter other details like description.
841 2. Enable the "Yes, this is a product with variants" toggle.
842 3. Under Product Options, enter "Metal" for the title, and enter "Gold" for the values.
843
844 Once you're done, click the Continue button.
845
846 ![Fill in the product details, enable the "Yes, this is a product with variants" toggle, and add the "Metal" option with "Gold" value](https://res.cloudinary.com/dza7lstvk/image/upload/v1738253520/Medusa%20Resources/Screenshot_2025-01-30_at_6.11.29_PM_lqxth9.png)
847
848 You can skip the next two steps by clicking the Continue button again, then the Publish button.
849
850 Once you're done, the product's page will open. You'll now add weight to the product's Gold variant. To do that:
851
852 - Scroll to the Variants section and find the Gold variant.
853 - Click on the three-dots icon at its right.
854 - Choose "Edit" from the dropdown.
855
856 ![Find the Gold variant in the Variants section, click on the three-dots icon, and choose "Edit"](https://res.cloudinary.com/dza7lstvk/image/upload/v1738254038/Medusa%20Resources/Screenshot_2025-01-30_at_6.19.52_PM_j3hjcx.png)
857
858 In the side window that opens, find the Weight field, enter the weight, and click the Save button.
859
860 ![Enter the weight in the Weight field, then click the Save button](https://res.cloudinary.com/dza7lstvk/image/upload/v1738254165/Medusa%20Resources/Screenshot_2025-01-30_at_6.22.15_PM_yplzdp.png)
861
862 Finally, you need to set fixed prices for the variant, even if they're just `0`. To do that:
863
864 1. Click on the three-dots icon at the top right of the Variants section.
865 2. Choose "Edit Prices" from the dropdown.
866
867 ![Click on the three-dots icon at the top right of the Variants section, then choose "Edit Prices"](https://res.cloudinary.com/dza7lstvk/image/upload/v1738255203/Medusa%20Resources/Screenshot_2025-01-30_at_6.39.35_PM_s3jpxh.png)
868
869 For each cell in the table, either enter a fixed price for the specified currency or leave it as `0`. Once you're done, click the Save button.
870
871 ![Enter fixed prices for the variant in the table, then click the Save button](https://res.cloudinary.com/dza7lstvk/image/upload/v1738255272/Medusa%20Resources/Screenshot_2025-01-30_at_6.40.45_PM_zw1l59.png)
872
873 You'll use this variant to add it to the cart later. You can find its ID by clicking on the variant, opening its details page. Then, on the details page, click on the icon at the right of the JSON section, and copy the ID from the JSON data.
874
875 ![Click on the icon at the right of the JSON section to copy the variant's ID](https://res.cloudinary.com/dza7lstvk/image/upload/v1738254314/Medusa%20Resources/Screenshot_2025-01-30_at_6.24.49_PM_ka7xew.png)
876
877 #### Retrieve Publishable API Key
878
879 All requests sent to API routes starting with `/store` must have a publishable API key in the header. This ensures the request's operations are scoped to the publishable API key's associated sales channels. For example, the products you retrieve are only those available in the key's sales channels.
880
881 <Note>
882
883 Medusa doesn't reject a variant added to a cart when its product isn't available in the cart's sales channel. Refer to the [Enforce Sales Channel Availability in Carts](../../../commerce-modules/cart/sales-channel-availability/page.mdx) guide to learn how to add that validation.
884
885 </Note>
886
887 To retrieve the publishable API key, on the Medusa Admin:
888
889 1. Click on Settings in the sidebar at the bottom left.
890 2. Click on Publishable API Keys from the sidebar, then click on a publishable API key in the list.
891
892 ![Click on publishable API keys in the Settings sidebar, then click on a publishable API key in the list](https://res.cloudinary.com/dza7lstvk/image/upload/v1738254523/Medusa%20Resources/Screenshot_2025-01-30_at_6.28.17_PM_mldscc.png)
893
894 3. Click on the publishable API key to copy it.
895
896 ![Click on the publishable API key to copy it](https://res.cloudinary.com/dza7lstvk/image/upload/v1738254601/Medusa%20Resources/Screenshot_2025-01-30_at_6.29.26_PM_vvatki.png)
897
898 You'll use this key when you test the API route.
899
900 ### Test API Route
901
902 To test out the API route, you need to create a cart. A cart must be associated with a region. So, to retrieve the ID of a region in your store, send a `GET` request to the `/store/regions` API route:
903
904 ```bash
905 curl 'localhost:9000/store/regions' \
906 -H 'x-publishable-api-key: {api_key}'
907 ```
908
909 Make sure to replace `{api_key}` with the publishable API key you copied earlier.
910
911 This will return a list of regions. Copy the ID of one of the regions.
912
913 Then, send a `POST` request to the `/store/carts` API route to create a cart:
914
915 ```bash
916 curl -X POST 'localhost:9000/store/carts' \
917 -H 'x-publishable-api-key: {api_key}' \
918 -H 'Content-Type: application/json' \
919 --data '{
920 "region_id": "{region_id}"
921 }'
922 ```
923
924 Make sure to replace `{api_key}` with the publishable API key you copied earlier, and `{region_id}` with the ID of a region from the previous request.
925
926 This will return the created cart. Copy the ID of the cart to use it next.
927
928 Finally, to add the Gold variant to the cart with a custom price, send a `POST` request to the `/store/carts/:id/line-items-metals` API route:
929
930 ```bash
931 curl -X POST 'localhost:9000/store/carts/{cart_id}/line-items-metals' \
932 -H 'x-publishable-api-key: {api_key}' \
933 -H 'Content-Type: application/json' \
934 --data '{
935 "variant_id": "{variant_id}",
936 "quantity": 1
937 }'
938 ```
939
940 Make sure to replace:
941
942 - `{api_key}` with the publishable API key you copied earlier.
943 - `{cart_id}` with the ID of the cart you created.
944 - `{variant_id}` with the ID of the Gold variant you created.
945
946 This will return the cart's details, where you can see in its `items` array the item with the custom price:
947
948 ```json title="Example Response"
949 {
950 "cart": {
951 "items": [
952 {
953 "variant_id": "{variant_id}",
954 "quantity": 1,
955 "is_custom_price": true,
956 // example custom price
957 "unit_price": 2000
958 }
959 ]
960 }
961 }
962 ```
963
964 The price will be the result of the calculation you've implemented earlier, which is the fixed price of the variant plus the real-time price of the metal, multiplied by the weight of the variant and the quantity added to the cart.
965
966 This price will be reflected in the cart's total price, and you can proceed to checkout with the custom-priced item.
967
968 ---
969
970 ## Next Steps
971
972 You've now implemented custom item pricing in Medusa. You can also customize the [storefront](../../../nextjs-starter/page.mdx) to use the new API route to add custom-priced items to the cart.
973
974 If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth learning of all the concepts you've used in this guide and more.
975
976 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).