www/apps/resources/app/commerce-modules/settings/user-preferences/page.mdx
export const metadata = {
title: User Preferences,
}
In this guide, you'll learn about user preferences in the Settings Module.
A user preference stores an arbitrary setting for a user as a key-value pair. For example, you can store a user's preferred theme or language.
The UserPreference data model represents a user preference. It denotes the user it belongs to through the user_id property, and it stores the setting's key and value in its key and value properties. A user can have only one preference per key.
The Settings Module's service provides methods to create, retrieve, update, and delete user preferences. Resolve the service from the Medusa container using Modules.SETTINGS.
Use the setUserPreference method to create or update a user preference by its key:
const preference = await settingsModuleService.setUserPreference(
"user_123",
"theme",
{ mode: "dark" }
)
Use the getUserPreference method to retrieve a user's preference by key:
const preference = await settingsModuleService.getUserPreference(
"user_123",
"theme"
)
This returns null if no preference exists for the specified user and key.
Use the createUserPreferences method to create one or more preferences at once:
const preferences =
await settingsModuleService.createUserPreferences([
{
user_id: "user_123",
key: "theme",
value: "dark",
},
])
Use the retrieveUserPreference method to retrieve a preference by its ID:
const preference =
await settingsModuleService.retrieveUserPreference("uspref_123")
Use the listUserPreferences method to list preferences with optional filters:
const preferences =
await settingsModuleService.listUserPreferences({
user_id: "user_123",
})
To retrieve a paginated list with the total count, use listAndCountUserPreferences:
const [preferences, count] =
await settingsModuleService.listAndCountUserPreferences(
{ user_id: "user_123" },
{ take: 20, skip: 0 }
)
Use the updateUserPreferences method to update existing preferences by their IDs:
const preferences =
await settingsModuleService.updateUserPreferences([
{
id: "uspref_123",
value: "light",
},
])
Use the deleteUserPreferences method to delete preferences by their IDs:
await settingsModuleService.deleteUserPreferences("uspref_123")
The Settings Module uses user preferences internally to track a user's active view for an entity and active layout scope for a zone.
Learn more about these concepts in the View Configurations and Layout Configurations documents.