shoppy.customer.subscribe(callback)
Subscribe to customer authentication state changes. The callback is called immediately with the current state, and then whenever the customer logs in, logs out, or their profile is updated.
Parameters
| Param | Type | Description |
|---|
callback | (customer: ShopifyCustomer | null) => void | Function called on auth changes |
Returns
() => void - Unsubscribe function.
Examples
Update navigation
shoppy.customer.subscribe((customer) => {
const nav = document.querySelector('#account-nav')
if (customer) {
nav.innerHTML = `
<span>Hi, ${customer.firstName || 'there'}!</span>
<a href="/account">My Account</a>
<button onclick="handleLogout()">Logout</button>
`
} else {
nav.innerHTML = `
<a href="/login">Login</a>
<a href="/register">Create Account</a>
`
}
})
React-style hook pattern
function useCustomer() {
let customer = shoppy.customer.getCached()
const listeners = new Set()
shoppy.customer.subscribe((c) => {
customer = c
listeners.forEach(fn => fn(customer))
})
return {
get customer() { return customer },
subscribe(fn) {
listeners.add(fn)
return () => listeners.delete(fn)
}
}
}
Cart with customer association
// When customer state changes, you might want to merge carts
shoppy.customer.subscribe(async (customer) => {
if (customer) {
// Customer just logged in - could sync with their saved cart
console.log('Customer logged in, cart ready for checkout')
} else {
// Customer logged out - cart persists for guest
console.log('Browsing as guest')
}
})
Cleanup subscription
// Store unsubscribe function
const unsubscribe = shoppy.customer.subscribe((customer) => {
updateUI(customer)
})
// Later, when component unmounts or page changes
unsubscribe()
The callback is invoked immediately with the current state (which may be null if .init() hasn’t been called yet). This lets you set up your UI without checking initial state separately.