A Medusa v2 custom fulfillment provider is a small module that extends AbstractFulfillmentProviderService, is registered under the Fulfillment Module in medusa-config.ts, and implements the methods Medusa calls through the order lifecycle. For a store shipping in India, this is how Shiprocket, Delhivery, Blue Dart, DTDC or a regional courier gets wired into Medusa; the default manual provider sends nothing anywhere. This guide covers the method surface, the folder layout, the registration, and why calculatePrice sometimes never runs.
The Fulfillment Module in v2 is deliberately empty out of the box. You get one provider, manual, which lets Admin mark an order as fulfilled by hand and nothing more. A live store needs a provider that talks to its courier. I lead Medusa v2 development work at MithTech, a team of Frappe specialists in Bengaluru who build mainly on Frappe and Medusa. This is the reference we give a developer writing their first provider.
What does a v2 fulfillment provider actually look like?
Answer
A Medusa v2 custom fulfillment provider is a TypeScript class that extends AbstractFulfillmentProviderService, declares a static identifier, and implements the lifecycle methods. Medusa calls them at set points: getFulfillmentOptions when an admin creates a shipping option, calculatePrice when a cart needs the price of a calculated option, createFulfillment when an order is fulfilled, cancelFulfillment when that fulfillment is cancelled. The provider is a module registered under the Fulfillment Module in medusa-config.ts.
The method surface, from the fulfillment provider reference and the base class source (checked against v2.21.2, 12 October 2026):
13 rows · click a column to sort
| Called when | ||
|---|---|---|
static identifier | Provider registration at boot | Required |
getFulfillmentOptions() | Admin creates a shipping option and picks from the provider's options | Throws |
validateOption(data) | A shipping option is created or updated | Throws |
validateFulfillmentData(optionData, data, context) | A shipping method is added to a cart | Throws |
canCalculate(data) | Admin creates a shipping option with price type calculated | Throws |
calculatePrice(optionData, data, context) | A cart needs the price of a calculated option | Throws |
createFulfillment(data, items, order, fulfillment) | A fulfillment is created for an order (Admin or a workflow) | Throws |
cancelFulfillment(data) | A fulfillment is cancelled | Throws |
createReturnFulfillment(fulfillment) | A return fulfillment is created | Throws |
getFulfillmentDocuments(data) | Fulfillment documents are requested | Returns [] |
getShipmentDocuments(data) | Shipment documents are requested | Returns [] |
getReturnDocuments(data) | Return documents are requested | Returns [] |
retrieveDocuments(fulfillmentData, documentType) | A document of a given type is requested | Throws |
The built-in manual provider (registered as fp_manual_manual) shows the minimum: it returns false from canCalculate, accepts any option and returns empty data and labels from createFulfillment. A real courier integration needs the rows that throw, for every flow your store uses.
How do you scaffold a v2 provider module?
For a Shiprocket provider:
src/modules/shiprocket-fulfillment/
├── service.ts # extends AbstractFulfillmentProviderService
└── index.ts # exports ModuleProvider(Modules.FULFILLMENT, { services: [ShiprocketService] })
src/modules/shiprocket-fulfillment/service.ts:
import { AbstractFulfillmentProviderService } from "@medusajs/framework/utils"
import { Logger } from "@medusajs/framework/types"
type InjectedDependencies = { logger: Logger }
type Options = { apiToken: string; pickupPostcode: string }
export default class ShiprocketService extends AbstractFulfillmentProviderService {
static identifier = "shiprocket"
protected logger_: Logger
protected options_: Options
constructor({ logger }: InjectedDependencies, options: Options) {
super()
this.logger_ = logger
this.options_ = options
}
// ... method implementations follow
}
src/modules/shiprocket-fulfillment/index.ts:
import { ModuleProvider, Modules } from "@medusajs/framework/utils"
import ShiprocketService from "./service"
export default ModuleProvider(Modules.FULFILLMENT, {
services: [ShiprocketService],
})
medusa-config.ts registration:
export default defineConfig({
modules: [
{
resolve: "@medusajs/medusa/fulfillment",
options: {
providers: [
{
resolve: "./src/modules/shiprocket-fulfillment",
id: "shiprocket",
options: {
apiToken: process.env.SHIPROCKET_API_TOKEN,
pickupPostcode: process.env.SHIPROCKET_PICKUP_POSTCODE,
},
},
],
},
},
],
})
Medusa's own example of this block lists the manual provider (resolve: "@medusajs/medusa/fulfillment-manual", id: "manual"). Keep it next to yours if the store still has shipping options that use it.
At boot, Medusa registers this as provider id fp_shiprocket_shiprocket (the pattern is fp_{identifier}_{id}). To use it, enable it on a stock location in Admin (Settings → Locations & Shipping → your location → Fulfillment providers). If it isn't in that list after a restart, the module isn't registered: check the resolve path.
What must getFulfillmentOptions return?
getFulfillmentOptions runs when an admin creates a shipping option in a service zone (for example "India domestic" or "Bengaluru local"). It returns the services your courier offers: for an aggregator like Shiprocket that could be surface, air and same-day; for Delhivery, express and standard. Only id is required by the type; name is what Admin shows.
async getFulfillmentOptions() {
return [
{ id: "shiprocket-surface", name: "Shiprocket Surface" },
{ id: "shiprocket-air", name: "Shiprocket Air" },
{ id: "shiprocket-express", name: "Shiprocket Express" },
]
}
When the admin creates a shipping option and picks "Shiprocket Air", Medusa stores that option object in the shipping option's data. You get it back as optionData in later calls.
validateOption vs validateFulfillmentData: what's the difference?
validateOption runs when a shipping option is created or updated: the admin is defining what "Shiprocket Air" means. Use it to reject a bad configuration, such as an ID your courier doesn't support:
async validateOption(data: Record<string, unknown>): Promise<boolean> {
const valid = ["shiprocket-surface", "shiprocket-air", "shiprocket-express"]
return valid.includes(data.id as string)
}
validateFulfillmentData runs when a customer's cart gets this shipping method. Use it to validate or enrich the per-cart data. The context carries the cart's id, shipping_address, items and the from_location:
import { ValidateFulfillmentDataContext } from "@medusajs/framework/types"
async validateFulfillmentData(
optionData: Record<string, unknown>,
data: Record<string, unknown>,
context: ValidateFulfillmentDataContext,
): Promise<Record<string, unknown>> {
// optionData = what the admin configured on the shipping option
// data = per-cart data sent from the storefront
// context = cart details: shipping_address, items, from_location
const pincode = context.shipping_address?.postal_code
if (!pincode) throw new Error("Shipping pincode required")
const serviceable = await this.checkServiceability(pincode)
if (!serviceable) throw new Error(`Shiprocket does not serve ${pincode}`)
return { ...data, verified_pincode: pincode }
}
The returned object is stored in the shipping method's data, and comes back to you in the later calls for this order.
How do canCalculate and calculatePrice work together?
For a courier where the cost depends on weight, distance and dimensions, you need calculated prices. Two things must be true:
1. The shipping option must have the price type calculated, not a fixed rate.
If the option was created with a fixed price (price_type: "flat"), Medusa uses that amount and never calls calculatePrice. That is by design, and it is the first thing to check.
2. Your provider implements both methods.
import {
CalculateShippingOptionPriceDTO,
CalculatedShippingOptionPrice,
CreateShippingOptionDTO,
} from "@medusajs/framework/types"
async canCalculate(data: CreateShippingOptionDTO): Promise<boolean> {
// Runs when the admin creates a calculated option.
// For Shiprocket, every option is quoted live.
return true
}
async calculatePrice(
optionData: CalculateShippingOptionPriceDTO["optionData"],
data: CalculateShippingOptionPriceDTO["data"],
context: CalculateShippingOptionPriceDTO["context"],
): Promise<CalculatedShippingOptionPrice> {
const pincode = context.shipping_address?.postal_code
// Variant weight is stored in whatever unit you use; grams here.
const totalWeight = (context.items ?? []).reduce(
(sum, item) => sum + (item.variant?.weight ?? 500) * Number(item.quantity),
0,
)
const quote = await this.getShiprocketQuote({
pickupPostcode: this.options_.pickupPostcode,
deliveryPostcode: pincode ?? "",
weightGrams: totalWeight,
courier: optionData.id,
})
return {
calculated_amount: quote.rate, // major units: 50 means ₹50
is_calculated_price_tax_inclusive: false,
}
}
Medusa v2 keeps amounts in major currency units (big numbers in Medusa): return ₹50 as 50. Multiplying by 100, as you would for a gateway that takes paise, shows the customer a price a hundred times too high. If calculatePrice throws or returns no calculated_amount, the cart operation that asked for the price fails, so give it a fallback when the courier API is down.
What does createFulfillment need to do?
createFulfillment runs when a fulfillment is created for an order: an admin fulfils items, or a workflow such as createOrderFulfillmentWorkflow does it. This is where you create the shipment at the courier and get back the AWB:
async createFulfillment(
data: Record<string, unknown>,
items: Array<Record<string, unknown>>,
order: Record<string, unknown> | undefined,
fulfillment: Record<string, unknown>,
): Promise<{ data: Record<string, unknown>; labels: Array<{ tracking_number: string; tracking_url: string; label_url: string }> }> {
// data = shipping method data (from validateFulfillmentData)
// items = the line items being fulfilled
// order = the parent order
// fulfillment = the fulfillment record being created
const shiprocketOrder = await this.createShiprocketOrder({
orderId: (order as { display_id: string }).display_id,
items,
shippingAddress: (order as { shipping_address: unknown }).shipping_address,
verifiedPincode: data.verified_pincode,
})
// Keep enough context to cancel or track later
return {
data: {
shiprocket_order_id: shiprocketOrder.order_id,
awb_code: shiprocketOrder.awb_code,
courier_company_id: shiprocketOrder.courier_company_id,
},
labels: [
{
tracking_number: shiprocketOrder.awb_code,
tracking_url: shiprocketOrder.tracking_url,
label_url: shiprocketOrder.label_url,
},
],
}
}
The returned data is stored on the fulfillment and handed back to cancelFulfillment. The labels are saved as the fulfillment's labels: tracking number, tracking URL and label URL.
cancelFulfillment is the mirror image. Medusa passes back the data you returned above, and you call the courier's cancel endpoint:
async cancelFulfillment(data: Record<string, unknown>): Promise<Record<string, unknown>> {
await this.cancelShiprocketOrder({
orderId: data.shiprocket_order_id as string,
awbCode: data.awb_code as string,
})
return { cancelled_at: new Date().toISOString() }
}
Why does my calculatePrice never get called?
Discussion #9495 (October 2024, Medusa 2.0) describes the symptom: the provider never loads, canCalculate and calculatePrice never run, and shipping options fail with "do not have a price". Back then the cause was in Medusa: backend support for calculated shipping prices hadn't shipped. The linked issue #9598 was closed as fixed in December 2024 (the 2.1 releases). On current versions, check these:
- The provider module isn't registered. If a log line in your constructor never appears at boot,
medusa-config.tsis not resolving the module. Check theresolvepath (relative to the config file), restartmedusa develop, and confirm the provider appears under the stock location's fulfillment providers in Admin. - The shipping option has a fixed price. In Admin (Settings → Locations & Shipping → your location → service zone), the option's price type must be Calculated. A fixed-rate option never calls
calculatePrice. Recreate the option as Calculated if it was set up wrong. canCalculatereturns false. It runs when the calculated option is created; if it returnsfalse, Medusa refuses the option. Returntruefor options your courier can quote.
FAQ
Do I need a separate module for each courier, or can one provider handle multiple?
Both work. One module with services: [ShiprocketService, DelhiveryService, DTDCService] is cleaner when the couriers share auth or config. Separate modules are cleaner when they have their own lifecycles or you want to enable them per environment. If unsure, start with separate modules; you can merge them later.
Where do I store the courier's API credentials?
In the options block of the provider's medusa-config.ts entry, read from environment variables. The constructor({ logger }, options) signature receives them. Don't hardcode credentials in the service file: they end up in git, are painful to rotate, and don't change with the environment.
How do I test the provider locally without hitting the courier's live API?
Two patterns. First, ask your courier or aggregator for a test or staging account and use it in development; not every one offers one, so check before you plan around it. Second, for unit tests, move the API client into its own class and mock it in your service tests. The provider itself is a thin adapter, easy to test with a stubbed client.
Can I use a v1 fulfillment plugin (npm package) on v2?
No. v1 fulfillment plugins extend a different base class (AbstractFulfillmentService) and use v1's dependency-injection conventions. The v2 base is AbstractFulfillmentProviderService from @medusajs/framework/utils, with a different method surface. Some community plugins have been ported, so check npm before writing from scratch, but a package written before v2 will not work.
Comments & ratings
No comments yet. Start a new discussion.
Manoj · Published on 9 August 2026
Worked with us? Leave a Google review