# Page Mapping

> Page mapping defines how URLs on your site map to Segmentify page types. When configured, the library automatically detects the current page and sends the appropriate tracking event.

## How It Works

When you provide a `pageMap` in your config, the library:

1. Matches the current URL against your configured patterns (or calls `externalObject`)
2. Determines the page type
3. Runs `preExecuteFunction` to gather page-specific data
4. Sends the tracking event
5. Runs `postExecuteFunction` after tracking

## Basic Page Map

```typescript
import { Initializer } from '@segmentify/integration';
import type { PageMap } from '@segmentify/integration';

const pageMap: PageMap = {
  'Home Page': {
    type: 'Home Page',
    pattern: ['/'],
  },
  'Product Page': {
    type: 'Product Page',
    pattern: ['/product/*', '/p/*'],
  },
  'Category Page': {
    type: 'Category Page',
    pattern: ['/category/*'],
  },
};

new Initializer({
  // ...required fields
  pageMap,
});
```

## Page Types

| Page Key                | Constant                           | Description            |
| ----------------------- | ---------------------------------- | ---------------------- |
| `Home Page`             | `PAGE_TYPES.HOME_PAGE`             | Site homepage          |
| `Product Page`          | `PAGE_TYPES.PRODUCT_PAGE`          | Product detail pages   |
| `Category Page`         | `PAGE_TYPES.CATEGORY_PAGE`         | Category listing pages |
| `Brand Page`            | `PAGE_TYPES.BRAND_PAGE`            | Brand-specific pages   |
| `Search Page`           | `PAGE_TYPES.SEARCH_PAGE`           | Search results         |
| `Empty Search Page`     | `PAGE_TYPES.EMPTY_SEARCH_PAGE`     | No-results search      |
| `Basket Page`           | `PAGE_TYPES.BASKET_PAGE`           | Shopping cart          |
| `Checkout Success Page` | `PAGE_TYPES.CHECKOUT_SUCCESS_PAGE` | Order confirmation     |
| `Register`              | `PAGE_TYPES.REGISTER_PAGE`         | User registration      |
| `Login`                 | `PAGE_TYPES.LOGIN_PAGE`            | User login             |
| `Logout`                | `PAGE_TYPES.LOGOUT_PAGE`           | User logout            |
| `404 Page`              | `PAGE_TYPES.FOUR_O_FOUR_PAGE`      | Not found              |
| `Blog Page`             | `PAGE_TYPES.BLOG_PAGE`             | Blog content           |
| `Profile Page`          | `PAGE_TYPES.PROFILE_PAGE`          | User profile           |
| `Unknown Page`          | `PAGE_TYPES.UNKNOWN_PAGE`          | Unmatched pages        |

## Pattern Matching

Match pages using glob-style URL patterns. Multiple patterns per page — matches if **any** pattern hits:

```typescript
'Product Page': {
  type: 'Product Page',
  pattern: ['/product/*', '/p/*', '/item/*'],
}
```

## External Object Matching

For SPAs where URL patterns aren't enough, determine the page type programmatically:

```typescript
'Product Page': {
  type: 'Product Page',
  externalObject: () => {
    const currentRoute = getAppRoute();
    return currentRoute.name === 'product' ? 'Product Page' : null;
  },
}
```

If `externalObject` returns `null`, the matcher falls through to the next page config.

## Pre/Post Execute Functions

`preExecuteFunction` runs **before** the tracking event — returns page-specific data:

```typescript
'Product Page': {
  type: 'Product Page',
  pattern: ['/product/*'],
  preExecuteFunction: async () => {
    const product = await getProductFromPage();
    return { productId: product.id, title: product.name, price: product.price };
  },
}
```

The return type is inferred from the page type:

| Page Type               | Expected Return Type                          |
| ----------------------- | --------------------------------------------- |
| `Product Page`          | `ProductViewPayload`                          |
| `Checkout Success Page` | `PurchasePayload`                             |
| `Basket Page`           | `BasketViewPayload`                           |
| `Register`              | `RegisterPayload`                             |
| `Login`                 | `Omit<RegisterPayload, 'isLogin'>`            |
| `Logout`                | `Omit<RegisterPayload, 'isLogin' \| 'email'>` |

`postExecuteFunction` runs **after** the event completes:

```typescript
'Product Page': {
  type: 'Product Page',
  pattern: ['/product/*'],
  postExecuteFunction: () => {
    console.log('Product page tracked');
  },
}
```

## Additional Options

| Option            | Type                                        | Description                   |
| ----------------- | ------------------------------------------- | ----------------------------- |
| `category`        | `PageKey`                                   | Page category override        |
| `brand`           | `string \| () => string \| Promise<string>` | Brand name or getter          |
| `subCategory`     | `string \| () => string \| Promise<string>` | Subcategory or getter         |
| `params`          | `object \| () => object \| Promise<object>` | Additional parameters         |
| `emptySearchPage` | `boolean`                                   | Flag for empty search results |

## Full Example

```typescript
const pageMap: PageMap = {
  'Home Page': {
    type: 'Home Page',
    pattern: ['/'],
  },
  'Product Page': {
    type: 'Product Page',
    pattern: ['/product/*'],
    preExecuteFunction: () => ({
      productId:
        document
          .querySelector('[data-product-id]')
          ?.getAttribute('data-product-id') || '',
      title: document.querySelector('h1')?.textContent || '',
      price: parseFloat(document.querySelector('.price')?.textContent || '0'),
    }),
  },
  'Basket Page': {
    type: 'Basket Page',
    pattern: ['/cart', '/basket'],
    preExecuteFunction: () => ({
      totalPrice: getCartTotal(),
      productList: getCartItems(),
    }),
  },
  'Checkout Success Page': {
    type: 'Checkout Success Page',
    pattern: ['/order/success*'],
    preExecuteFunction: () => ({
      totalPrice: getOrderTotal(),
      orderNo: getOrderNumber(),
      productList: getOrderItems(),
    }),
  },
  'Search Page': {
    type: 'Search Page',
    pattern: ['/search*'],
  },
};
```

## See Also

- [SPA Mode](/04-spa-mode) — How page detection works with client-side routing
