Apply Discount Code
Apply a coupon or affiliate code to the cart.
Updated
On this page
Overview
Apply a discount or coupon code to the cart. The discount is validated and applied server-side.
SDK Usage
import dash from "@/lib/dash"
// Apply discount
const { message, cart } = await dash.cart.applyDiscount("SAVE20")
// cart.discount_code = "SAVE20"
// cart.discount_amount = "15.00"
// Remove discount
const result = await dash.cart.removeDiscount()
Validate Before Applying
You can validate a code before applying it to show the customer what they'll save:
// This doesn't apply the code — just checks it
const response = await fetch("/storefront/discount/validate", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-API-Key": apiKey,
},
body: JSON.stringify({
code: "SAVE20",
subtotal: "99.99",
}),
})
const result = await response.json()
// result = {
// valid: true,
// discount_amount: "15.00",
// is_percentage: true,
// rate: "20",
// code: "SAVE20"
// }
Discount Code Input Example
"use client"
import { useState } from "react"
import dash from "@/lib/dash"
export function DiscountCodeInput({ onApplied }) {
const [code, setCode] = useState("")
const [error, setError] = useState("")
async function handleApply() {
try {
setError("")
const { cart } = await dash.cart.applyDiscount(code)
onApplied(cart)
} catch (err) {
setError(err.message) // "Invalid code" or "Code expired"
}
}
return (
<div>
<input value={code} onChange={e => setCode(e.target.value)}
placeholder="Discount code" />
<button onClick={handleApply}>Apply</button>
{error && <p className="text-red-500">{error}</p>}
</div>
)
}
REST API
# Apply discount
POST /storefront/cart/{cart_id}/apply-discount
Content-Type: application/json
X-API-Key: pk_live_your_key
{ "code": "SAVE20" }
# Remove discount
POST /storefront/cart/{cart_id}/remove-discount
X-API-Key: pk_live_your_key
# Validate without applying
POST /storefront/discount/validate
Content-Type: application/json
X-API-Key: pk_live_your_key
{ "code": "SAVE20", "subtotal": "99.99" }
Next Steps
- Discount Codes — Types of discounts available
- Create Order — Proceed to checkout with discount applied
- Validate Code — Code validation details