Essentials

Personalization

Deliver personalized content experiences with Contentstack Personalize integration, including user attributes, events, and variant-based content delivery.

Nuxt Contentstack provides seamless integration with Contentstack Personalize, enabling you to deliver personalized content experiences based on user attributes, behavior, and preferences.

Master Personalization: Deepen your understanding of Contentstack Personalize with the Personalize Foundations Academy course. Learn to set up projects, configure segmented experiences, run A/B tests, and leverage attributes and audiences effectively.

Overview

The Nuxt module automatically initializes the Personalize Edge SDK and provides easy access through the $contentstack.personalizeSdk object (client-side only; server-side personalization is handled by the built-in middleware).

Key features:

  • User Attributes: Set and track user properties
  • Event Tracking: Monitor user interactions and conversions
  • Variant Delivery: Serve different content based on user segments
  • Real-time Personalization: Dynamic content adaptation

How It Works

When personalization is enabled, the module:

  1. Registers a server middleware that intercepts all requests, initializes the Personalize Edge SDK, extracts variant aliases from the request, and stores them in event.context.p13n
  2. Provides the Personalize SDK on the client through useContentstack().personalizeSdk
  3. Automatically applies variant aliases to all entry composable queries (e.g., useGetEntry, useGetEntryByUrl, useGetEntries)
  4. Manages cookies for variant persistence across requests

Quick Setup

1. Enable Personalization

nuxt.config.ts
export default defineNuxtConfig({
  modules: ['nuxt-contentstack'],

  'nuxt-contentstack': {
    apiKey: process.env.NUXT_CONTENTSTACK_API_KEY,
    deliveryToken: process.env.NUXT_CONTENTSTACK_DELIVERY_TOKEN,
    environment: 'production',

    personalization: {
      enable: true,
      projectUid: process.env.NUXT_CONTENTSTACK_PERSONALIZE_PROJECT_UID
    }
  }
})

2. Environment Variables

.env
NUXT_CONTENTSTACK_PERSONALIZE_PROJECT_UID=your_project_uid
Project UID: Find your project UID in Contentstack under Personalize → Project Settings.

Basic Usage

Setting User Attributes

composables/usePersonalization.ts
export const usePersonalization = () => {
  const { personalizeSdk } = useContentstack()

  const setUserAttributes = async (attributes: Record<string, any>) => {
    if (personalizeSdk) {
      await personalizeSdk.set(attributes)
    }
  }

  return { setUserAttributes }
}

Tracking Events

components/ProductCard.vue
<script setup>
const { personalizeSdk } = useContentstack()

const trackPurchase = async (productId: string, amount: number) => {
  await personalizeSdk?.triggerEvent('purchase')
}

const trackImpression = async (experienceShortUid: string) => {
  await personalizeSdk?.triggerImpression(experienceShortUid)
}
</script>

Core SDK Methods

Client-side only: The personalizeSdk instance is only available on the client. On the server, personalization is handled automatically by the built-in middleware. Always check personalizeSdk is not null before calling methods.

Available Methods

MethodDescription
set(attributes)Set user attributes for targeting
triggerEvent(eventKey)Track a conversion event
triggerImpression(experienceShortUid)Track an experience impression
triggerImpressions(options)Track multiple impressions at once
setUserId(userId, options?)Set a custom user ID
getUserId()Get the current user ID
getVariants()Get all active variants
getVariantAliases()Get variant aliases for CMS queries
getVariantParam()Get the variant query parameter string
getActiveVariant(experienceShortUid)Get active variant for a specific experience
addStateToResponse(response)Add personalization state to a Response object

User Attributes

Set user attributes for personalization targeting:

const { personalizeSdk } = useContentstack()

// Set demographic attributes
await personalizeSdk.set({
  age: 30,
  location: 'San Francisco',
  membership: 'premium'
})

// Set behavioral attributes
await personalizeSdk.set({
  page_views: 15,
  interests: ['technology', 'design'],
  last_visit: new Date().toISOString()
})

Event Tracking

Track user interactions and conversions:

const { personalizeSdk } = useContentstack()

// Track conversion events
await personalizeSdk.triggerEvent('signup')
await personalizeSdk.triggerEvent('purchase')
await personalizeSdk.triggerEvent('newsletter_subscribe')

// Track experience impressions
const experienceShortUid = 'a' // From Contentstack Personalize
await personalizeSdk.triggerImpression(experienceShortUid)

// Track multiple impressions at once
await personalizeSdk.triggerImpressions({
  experienceShortUids: ['a', 'b']
})

Variant Management

Access active variants for personalized content:

const { personalizeSdk, variantAlias } = useContentstack()

// Get all active variants
const variants = personalizeSdk.getVariants() // {a: '0', b: '1'}

// Get variant aliases for CMS queries
const aliases = personalizeSdk.getVariantAliases()
// ['cs_personalize_a_0', 'cs_personalize_b_1']

// Get the variant query parameter string
const variantParam = personalizeSdk.getVariantParam()

// Get active variant for specific experience
const activeVariant = personalizeSdk.getActiveVariant('a') // '0'

// Access the reactive variant alias used by composables
console.log('Current alias:', variantAlias?.value)

Personalized Content Fetching

Automatic Variant Application

All composables automatically apply active variants. The module adds include_applied_variants and include_dimension parameters and calls .variants() on queries when a variant alias is present:

pages/personalized-page.vue
<script setup>
// Content will be personalized based on user attributes
const { data: content } = await useGetEntryByUrl({
  contentTypeUid: 'landing_page',
  url: '/home'
})

// Variant aliases are automatically applied
const { variantAlias } = useContentstack()
console.log('Active variants:', variantAlias?.value)
</script>

<template>
  <div v-if="content">
    <!-- Renders personalized variant -->
    <Hero v-bind="content.hero" />
  </div>
</template>

User Identity

Manage user identity for cross-session personalization:

const { personalizeSdk } = useContentstack()

// Set a custom user ID
await personalizeSdk.setUserId('user-123', {
  preserveUserAttributes: true // Keep existing attributes
})

// Get the current user ID
const userId = personalizeSdk.getUserId()

Manual Variant Handling

For advanced use cases:

// Get current variants
const { personalizeSdk } = useContentstack()
const variantAliases = personalizeSdk.getVariantAliases()

// Use in custom queries
const { data } = await $fetch('/api/content', {
  query: { variants: variantAliases.join(',') }
})

Real-world Examples

User Onboarding Flow

components/OnboardingFlow.vue
<script setup>
const { personalizeSdk } = useContentstack()

const completeOnboardingStep = async (step: string) => {
  // Set user attributes
  await personalizeSdk?.set({
    onboarding_step: step,
    onboarding_completed: step === 'complete'
  })

  // Track event
  await personalizeSdk?.triggerEvent('onboarding_step_completed')
}

// Track page view
onMounted(async () => {
  await personalizeSdk?.set({
    last_page: 'onboarding',
    page_views: (currentPageViews || 0) + 1
  })
})
</script>

Product Recommendations

components/Recommendations.vue
<script setup>
const { personalizeSdk } = useContentstack()

// Set user preferences
const updatePreferences = async (categories: string[]) => {
  await personalizeSdk?.set({
    preferred_categories: categories,
    last_updated: new Date().toISOString()
  })
  
  // Refetch personalized recommendations
  await refresh()
}

// Fetch personalized content
const { data: recommendations } = await useGetEntries({
  contentTypeUid: 'product_recommendation',
  limit: 6
})
</script>

Best Practices

Performance

  • Batch attribute updates when possible
  • Cache personalized content appropriately
  • Use specific variant queries only when needed

Privacy

  • Implement consent management
  • Only collect necessary attributes
  • Respect user privacy preferences

Development

  • Test personalization in preview mode
  • Monitor performance impact

Troubleshooting

Check if personalization is enabled:

const { personalizeSdk } = useContentstack()
console.log(personalizeSdk ? 'Enabled' : 'Disabled')

Verify variant delivery:

const { variantAlias, personalizeSdk } = useContentstack()
console.log('Current variant alias:', variantAlias?.value)
console.log('Active variants:', personalizeSdk?.getVariants())

Debug attribute setting:

const { personalizeSdk } = useContentstack()
await personalizeSdk?.set({ test_attribute: 'value' })
// Check network requests in browser developer tools

Next Steps

Live Preview

Combine personalization with real-time content editing.