Skip to main content

Commerce

Medusa v2 Custom Fulfillment Provider for India: A Complete Guide (2026)

Build a Medusa v2 fulfillment provider for an Indian courier: every AbstractFulfillmentProviderService method, the folder shape, config and calculatePrice.

Updated 12 Oct 202612 min readBy ManojFirst published 9 Aug 2026

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 identifierProvider registration at bootRequired
getFulfillmentOptions()Admin creates a shipping option and picks from the provider's optionsThrows
validateOption(data)A shipping option is created or updatedThrows
validateFulfillmentData(optionData, data, context)A shipping method is added to a cartThrows
canCalculate(data)Admin creates a shipping option with price type calculatedThrows
calculatePrice(optionData, data, context)A cart needs the price of a calculated optionThrows
createFulfillment(data, items, order, fulfillment)A fulfillment is created for an order (Admin or a workflow)Throws
cancelFulfillment(data)A fulfillment is cancelledThrows
createReturnFulfillment(fulfillment)A return fulfillment is createdThrows
getFulfillmentDocuments(data)Fulfillment documents are requestedReturns []
getShipmentDocuments(data)Shipment documents are requestedReturns []
getReturnDocuments(data)Return documents are requestedReturns []
retrieveDocuments(fulfillmentData, documentType)A document of a given type is requestedThrows

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:

TypeScript
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:

TypeScript
import { ModuleProvider, Modules } from "@medusajs/framework/utils"
import ShiprocketService from "./service"

export default ModuleProvider(Modules.FULFILLMENT, {
  services: [ShiprocketService],
})

medusa-config.ts registration:

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

TypeScript
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:

TypeScript
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:

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

TypeScript
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:

TypeScript
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:

TypeScript
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:

  1. The provider module isn't registered. If a log line in your constructor never appears at boot, medusa-config.ts is not resolving the module. Check the resolve path (relative to the config file), restart medusa develop, and confirm the provider appears under the stock location's fulfillment providers in Admin.
  2. 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.
  3. canCalculate returns false. It runs when the calculated option is created; if it returns false, Medusa refuses the option. Return true for 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.

Live demo

Your next step

Wiring up a custom fulfillment provider on Medusa v2?

Sales and orders

An online order, start to finish

5 screens · about 8 min · you end with a payment recorded

See it live

Sales OrderTo deliver and bill

The customer's confirmed order: who it's for, the items at their price list and when it's due.

Customer
A demo customer
Prices
From their price list

Mith Demo Traders · demo company

Commerce

Now see what a store you own would look like

How we build and run Medusa storefronts and B2B portals connected to ERPNext, and when staying on a hosted platform is the better call.

Comments & ratings

No comments yet. Start a new discussion.

0

Manoj · Published on 9 August 2026

Worked with us? Leave a Google review

Questions about this? Talk to the team.

Book a 30-minute Google Meet, WhatsApp us, or send a message. The engineer who works on this replies.

Send us a message

Your details go to our team's CRM and are used only to reply.