@builder.io/personalization-utils

中文文档
4.0.0发布于 2024/10/04TypeScriptCommonJS近 30 天下载 2698

Utils for personalization at the edge

原始使用文档

Builder Personalization Utils

A collection of handy utilities when working with delivering personalized Builder content at the edge.

npm install @builder.io/personalization-utils

How to start with personalized rewrites?

This utility library helps you encode/decode targeting attributes as parts of the URL to allow for caching (or statically generating) render results, it should be used in middleware in combination with a page path handler (for e.g a catch all page pages/[[...path]].jsx):

import { parsePersonalizedURL } from '@builder.io/personalization-utils/next'
// in pages/[[...path]].jsx
export async function getStaticProps({ params }) {
  const { attributes } = parsePersonalizedURL(params?.path);
  const page =
    (await builder
      .get('page', {
        apiKey: builderConfig.apiKey,
        userAttributes: attributes,
        // cachebust is not advised outside static rendering contexts.
        cachebust: true,
      })
      .promise()) || null

  return {
    props: {
      page,
    },
    // Next.js will attempt to re-generate the page:
    // - When a request comes in
    // - At most once every 1 second
    revalidate: 1,
  }
}

export function getStaticPaths() {
  return {
    paths: [],
    fallback: true,
  }
}

export default function Path({ page }) {
  return  <BuilderComponent model="page" content={page} />
}

Now that we have a path for rendering builder content ready, let's route to it in the middleware:

import { getPersonalizedURL } from '@builder.io/personalization-utils/next'

const excludededPrefixes = ['/favicon', '/api'];

export default function middleware(request) {
  const url = request.nextUrl
  if (shouldRewrite(url.pathname)) {
    const personalizedURL = getPersonalizedURL(request)
    return NextResponse.rewrite(personalizedURL)
  }
  return NextResponse.next();
}
const audience = await myCDP.identifyAudience(userID);
// this will include the `audience` in all api calls and save it in a cookie `builder.userAttributes`
builder.setUserAttributes({ audience })

Once the cookie is set, all builder content matching from now on will weigh in the current audience segment.

Using trimHtml for Dynamic Containers and A/B Tests

The trimHtml function is a utility for handling dynamic personalization containers and A/B test variants in your HTML content. It's particularly useful for processing personalized content at the edge or in server-side rendering scenarios.

Usage

import { trimHtml } from '@builder.io/personalization-utils'

const fullHTML = '... your full HTML string with personalization containers and A/B test variants ...';
const userAttributes = {
  audience: 'segment-a',
  date: '2023-06-15T12:00:00Z'
};
const abTests = {
  'content-id-1': 'variant-a',
  'content-id-2': 'variant-b'
};

const { html } = trimHtml(fullHTML, { userAttributes, abTests });

To get the userAttributes, you should parse the builder.userAttributes cookie. Here's an example of how you might do this:

import { parse } from 'cookie'

function getUserAttributes(req) {
  const cookies = parse(req.headers.cookie || '');
  const builderAttributes = cookies['builder.userAttributes'];
  return builderAttributes ? JSON.parse(builderAttributes) : {};
}

// Then in your request handler:
const userAttributes = getUserAttributes(req);

To get the abTests data, you can parse the relevant cookies like this:

import { parse } from 'cookie'

function getAbTests(req) {
  const cookies = parse(req.headers.cookie || '');
  const abTests = Object.entries(cookies).reduce((acc, [cookieName, cookieValue]) => {
    if (cookieName.startsWith('builder.tests')) {
      return {
        ...acc,
        [cookieName.split('.').slice(-1)[0]]: cookieValue
      }
    }
    return acc;
  }, {});
  return abTests;
}

// Then in your request handler:
const abTests = getAbTests(req);
const { html } = trimHtml(fullHTML, { userAttributes, abTests });

The trimHtml function processes the HTML in the following order:

  1. It first applies A/B test variants based on the provided abTests object.
  2. Then it evaluates personalization containers against the provided user attributes.
  3. Finally, it returns a new HTML string with the appropriate personalized content and A/B test variants.

This approach allows you to deliver personalized content and A/B test variants while still leveraging edge caching or static site generation, as the personalization and A/B test logic is applied after the initial HTML is generated.

版本与发布记录

@builder.io/personalization-utils 共发布 63 个版本,首次发布于 2021/10/07;过去 12 个月发布了 0 个版本。

版本发布日期距今
4.0.0latest2024/10/042 年前
3.0.02024/09/202 年前
2.0.1-0dev2023/02/283 年前
2.0.02022/09/164 年前
1.1.12022/08/314 年前
1.1.1-192022/08/304 年前

关于 @builder.io/personalization-utils 的常见问题

@builder.io/personalization-utils 是什么?

Utils for personalization at the edge

如何安装 @builder.io/personalization-utils?

在项目目录运行 npm install @builder.io/personalization-utils,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@builder.io/sdk(^1.1.20)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@builder.io/personalization-utils 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@builder.io/personalization-utils 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@builder.io/personalization-utils 可以商用吗?

@builder.io/personalization-utils 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@builder.io/personalization-utils 的下载量有多少?

根据 npm 官方下载统计,@builder.io/personalization-utils 在 2026/10/09 – 2026/11/07 这 30 天内被下载 2,698 次,日均约 90 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@builder.io/personalization-utils 还在维护吗?

最新版本 4.0.0 发布于 2024/10/04(2 年前);至今共发布 63 个版本,其中过去 12 个月发布了 0 个;首次发布于 2021/10/07。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。