### Basic SearchHeadlessProvider Setup
Source: https://hitchhikers.yext.com/docs/search/searchheadlessprovider
Wrap your application's templates with SearchHeadlessProvider to give components access to a SearchHeadless instance and hooks. This example shows a common setup for Yext Pages.
```typescript
import {
provideHeadless,
SearchHeadlessProvider,
} from "@yext/search-headless-react";
const searcher = provideHeadless({
apiKey: YEXT_PUBLIC_SEARCH_API_KEY,
experienceKey: "ecomm-search",
locale: "en",
});
const Main = ({ children }: { children: React.ReactNode }) => {
return (
{children}
);
};
```
--------------------------------
### Install Yext CLI on Windows using MSI Installer
Source: https://hitchhikers.yext.com/docs/cli/installation/installation
Steps to install the Yext CLI on Windows using the provided MSI installer. After installation, initialize the CLI using Powershell.
```powershell
yext init
```
--------------------------------
### Yext Resources Command Help Output
Source: https://hitchhikers.yext.com/docs/cli/getting-started/getting-started
This is an example of the output you will see when running `yext resources --help`. It details the purpose of the command group, lists available commands like `pull` and `apply`, and explains how to get further help.
```text
This is a beta version of the Yext Command Line Interface
The resources command group provides built-in, cross-service commands that enable project-wide configuration to be managed as code.
The fundamental operations are:
pull - pulling/fetching configuration from the services in a resource-oriented model and storing them in code files
apply - making the configuration on the server match the state defined in source files. (This includes diff with the use of dry-run).
Usage:
yext resources [command]
Available Commands:
apply Apply configurations from source directory
diff Diff local resources against resources in Yext
pull Pull configurations to destination directory
Flags:
-h, --help help for resources
Use "yext resources [command] --help" for more information about a command.
```
--------------------------------
### Filter Entities by Start Time Before a Year
Source: https://hitchhikers.yext.com/docs/contentdeliveryapis/legacy/entities
Use ordered searches with date types to find entities whose start times are before a specified year. This example matches start times before 2018.
```json
{
"time.start": {
"$lt": "2018"
}
}
```
--------------------------------
### Full HTML Page Example with SearchBar Component
Source: https://hitchhikers.yext.com/docs/search/search-ui-sdk-components-overview
This example demonstrates a complete HTML page structure that includes the necessary HTML for a component's container and the JavaScript to initialize the Answers SDK and add a SearchBar component.
```html
```
--------------------------------
### Example Filter for Events
Source: https://hitchhikers.yext.com/docs/contentdeliveryapis/legacy/entities
This example demonstrates a complex filter combining entity type, name prefix, age range, and start time.
```json
{
"entityTypes": "event",
"name": {
"$startsWith": "Century"
},
"age": {
"$lt": 20,
"$gt": 10
},
"time.start": {
"$gte": "2018-08-28T19:00"
}
}
```
--------------------------------
### Initialize Yext Credentials
Source: https://hitchhikers.yext.com/docs/cli/universal-command-group/universal-commands
Use this command to set up or select Yext credentials. It guides you through selecting a universe (production or sandbox), choosing or creating credentials, and linking to a Yext account.
```bash
yext init [ACCOUNT-ID] [flags]
```
--------------------------------
### Filter Entities by Year
Source: https://hitchhikers.yext.com/docs/contentdeliveryapis/legacy/entities
Query entities based on the year of their start times. This example shows how to match all start times within the year 2018.
```json
{
"time.start": {
"$eq": "2018"
}
}
```
--------------------------------
### Live Preview Configuration
Source: https://hitchhikers.yext.com/docs/pages/site-configuration?target=serving
Defines the command to run a local web server for live preview. The `serveCommand` must start a server on port 8080. An optional `setupCommand` can be used for pre-serve tasks.
```yaml
livePreviewConfiguration:
serveCommand: "npm run dev -- --port 8080"
# setupCommand: ":"
```
--------------------------------
### Complex Entity Filtering Example
Source: https://hitchhikers.yext.com/docs/contentdeliveryapis/legacy/entities
This example demonstrates a multi-criteria filter for entities, including type, name prefix, age range, and start time.
```json
{
"entityTypes": "event",
"name": {
"$beginsWith": "Century"
},
"age": {
"$gte": 10,
"$lte": 20
},
"age_min": {
"$gte": 5,
"$lte": 7
},
"time.start": {
"$gte": "2018-08-28T19:00"
}
}
```
--------------------------------
### Update ci/serve_setup.sh for Development Preview
Source: https://hitchhikers.yext.com/docs/search/changelog-hitchhikers-theme?target=send-new-attributes-with-analytics-events-on-thumbs-up-down
Modify the `ci/serve_setup.sh` script to include `export IS_DEVELOPMENT_PREVIEW='true'` for auto-initialization in the Yext code editor.
```shell
#!/bin/sh
export NODE_OPTIONS="--max-old-space-size=1024"
#This will use development mode while in the Yext code editor. Set to "false" to test the production build.export IS_DEVELOPMENT_PREVIEW='true'
npx jambo build
grunt webpack
```
--------------------------------
### Plugin Configuration Example
Source: https://hitchhikers.yext.com/docs/pages/ci-configuration
An example of how to configure plugins for the Yext CI build process. It specifies the plugin name, source files, the event to trigger on, and the function to execute.
```json
"plugins": [
{
"pluginName": "Generator",
"sourceFiles": [
{
"root": "dist/plugin",
"pattern": "*{.ts,.json}"
},
{
"root": "dist",
"pattern": "assets/{server,static,renderer}/**/*{.js,.css}"
}
],
"event": "ON_PAGE_GENERATE",
"functionName": "Generate"
}
]
```
--------------------------------
### Pure JS Template Example with Handlebars
Source: https://hitchhikers.yext.com/docs/pages/pure-js-rendering
This example shows how to use Handlebars as a templating language within a pure JavaScript render function. Ensure Handlebars is installed via npm.
```typescript
import * as hbs from "handlebars";
export const render: Render = ({ document }) => {
const hbsTemplateString = `
{{name}}
{{name}}
{{address.line1}}
{{address.city}}, {{address.region}}
`;
// Compile Template
const hbsTemplate = hbs.compile(hbsTemplateString);
// Render HTML
return hbsTemplate(document);
};
// NO DEFAULT EXPORT
```
--------------------------------
### Configure ci/serve_setup.sh for Live Preview
Source: https://hitchhikers.yext.com/docs/search/changelog-theme-live-preview
To fix the 'Server application unavailable' error, remove the line `npm install -g serve` from the `ci/serve_setup.sh` file. This ensures the correct version of 'serve' is used.
```bash
#!/bin/sh
npx jambo build
grant webpack
```
--------------------------------
### Initialize Search with a SearchBar Component
Source: https://hitchhikers.yext.com/docs/search/search-ui-sdk-components-overview
This is a basic example of initializing the Answers SDK and adding a SearchBar component. Components should always be added within the `onReady` function.
```javascript
ANSWERS.init({
apiKey: "df4b24f4075800e5e9705090c54c6c13",
experienceKey: "rosetest",
businessId: "2287528",
experienceVersion: "PRODUCTION",
onReady: function() {
ANSWERS.addComponent("SearchBar", {
container: ".search-container",
});
},
});
```
--------------------------------
### Include Search UI SDK
Source: https://hitchhikers.yext.com/docs/search/search-ui-sdk-get-started
Include the Search UI SDK script in your HTML file to get started.
```html
```
--------------------------------
### Get by ID Request Example
Source: https://hitchhikers.yext.com/docs/streams
Demonstrates how to fetch one or more records by their primary keys. Multiple IDs can be specified using commas or semicolons.
```APIDOC
## GET /v2/accounts/me/api/exampleEndpoint/{ids}
### Description
Fetches one or more records by their primary keys.
### Method
GET
### Endpoint
`https://cdn.yext.com/v2/accounts/me/api/exampleEndpoint/id1;id2;id3`
### Parameters
#### Path Parameters
- **ids** (string) - Required - A comma or semicolon-separated list of primary keys.
#### Query Parameters
- **api_key** (string) - Required - Your Yext API key.
- **v** (string) - Required - The API version (e.g., `20200408`).
### Response
#### Success Response (200)
- **data** (object) - Contains the requested records.
```
--------------------------------
### Set up AnalyticsProvider
Source: https://hitchhikers.yext.com/docs/pages/implement-yext-analytics
Wrap your page components with `` to bootstrap the Analytics reporter. Ensure you replace 'REPLACE_WITH_API_KEY' with your actual API key.
```jsx
import { AnalyticsProvider } from "@yext/pages-components";
import { TemplateProps } from "@yext/pages";
{children}
```
--------------------------------
### Ticket Clicks Example
Source: https://hitchhikers.yext.com/docs/analytics/event-listings-metrics
Represents the number of clicks on a 'get tickets' button. Use this to measure the effectiveness of your calls to action for ticket purchases.
```json
{"Ticket Clicks": 0, "day": "2021-10-24"}
```
--------------------------------
### Render Hierarchical Facets with `hierarchicalFieldIds`
Source: https://hitchhikers.yext.com/docs/search/hierarchicalfacet-react-component
Use the `hierarchicalFieldIds` prop on the `` component to render hierarchical facets. This example shows basic setup with `SearchBar` and `VerticalResults`.
```jsx
import { useSearchActions } from "@yext/search-headless-react";
import {
SearchBar,
StandardCard,
Facets,
VerticalResults,
} from "@yext/search-ui-react";
import { useEffect } from "react";
const App = (): JSX.Element => {
const searchActions = useSearchActions();
useEffect(() => {
searchActions.setVertical("products");
}, []);
return (
);
};
export default App;
```
--------------------------------
### Site-Specific Configuration Example (`ci.json`)
Source: https://hitchhikers.yext.com/docs/pages/website-fleet-management
Example of a `ci.json` file for a specific site (`www.example-1.com`) within the `sites-config` directory. It defines artifact structures, build commands, and other configurations for that site.
```json
{
"artifactStructure": {
"assets": [
{
"root": "dist",
"pattern": "assets/**/*"
}
],
"features": "sites-config/www.example-1.com/features.json",
"plugins": [
{
"pluginName": "Generator",
"sourceFiles": [
{
"root": "dist/plugin",
"pattern": "*{.ts,.json}"
},
{
"root": "dist",
"pattern": "assets/{server,static,renderer}/**/*{.js,.css}"
}
],
"event": "ON_PAGE_GENERATE",
"functionName": "Generate"
}
]
},
"dependencies": {
"installDepsCmd": "npm install",
"requiredFiles": ["package.json", "package-lock.json", ".npmrc"]
},
"buildArtifacts": {
"buildCmd": "npx pages build --scope www.example-1.com"
},
"livePreview": {
"serveSetupCmd": ":"
}
}
```
--------------------------------
### Example Request for Reviews Aggregate Data
Source: https://hitchhikers.yext.com/docs/streams/reviewsagg-source
GET request to query the 'reviewsAggByState' Content Endpoint for entities in New York (NY). Requires an API key and specifies the API version.
```http
GET https://cdn.yextapis.com/v2/accounts/me/api/reviewsAggByState?api_key={api_key}&v=20200408&entity.address.region=NY
```
--------------------------------
### Global Configuration Example
Source: https://hitchhikers.yext.com/docs/search/theme-global-locale-config
Specify shared properties like SDK version, API keys, and tracking settings. Many properties are optional and can be auto-populated.
```json
{
"sdkVersion": "1.16", // The version of the Answers SDK to use
// "token": "", // |e
// "apiKey": "", // The answers api key found on the experiences page. This will be provided automatically by the Yext CI system
// "experienceVersion": "", // the Answers Experience version to use for API requests. This will be provided automatically by the Yext CI system
// "environment": "production", // The environment to run on for this Answers Experience. (i.e. 'production' or 'sandbox')
// "cloudRegion": "us", // The cloud region to use for this Answers Experience. (i.e. 'us' or 'eu')
// "cloudChoice": "multi", // The cloud provider to use for this Answers Experience. (i.e. 'multi' or 'gcp')
// "businessId": "", // The business ID of the account. This will be provided automatically by the Yext CI system
// "initializeManually": true, // If true, the experience must be started by calling AnswersExperience.init() or AnswersExperienceFrame.init() for iframe integrations.
// "useJWT": true, // Whether or not to enable JWT. If true, the apiKey will be hidden from the build output and the token must be specified through manual initialization.
// "useGenerativeDirectAnswers": true, // Whether or not to use generative direct answers when applicable
"sessionTrackingEnabled": true, // Whether or not session tracking is enabled for all pages
"analyticsEventsEnabled": true, // Whether or not to submit user interaction analytics events
"logo": "", // The link to the logo for open graph meta tag - og:image.
"favicon": "",
"googleTagManagerName": "dataLayer", // The name of your Google Tag Manager data layer
"googleTagManagerId": "", // The container id associated with your Google Tag Manager container
"googleAnalyticsId": "", // The tracking Id associated with your Google Analytics account
"conversionTrackingEnabled": true // Whether or not conversion tracking is enabled for all pages
}
```
--------------------------------
### Initialize Search UI SDK and Add Components
Source: https://hitchhikers.yext.com/docs/search/search-ui-sdk-get-started
Initialize the JavaScript library with your API key, experience key, and business ID. Then, add the desired search components to their respective containers.
```javascript
ANSWERS.init({
apiKey: "3517add824e992916861b76e456724d9", //sample test experience
experienceKey: "answers-js-docs", //sample test experience
businessId: "3215760", //sample test experience
experienceVersion: "PRODUCTION",
onReady: function () {
// init components
this.addComponent("SearchBar", {
container: ".search-bar"
});
this.addComponent("SpellCheck", {
container: ".spell-check"
});
this.addComponent("DirectAnswer", {
container: ".direct-answer"
});
this.addComponent("UniversalResults", {
container: ".universal-results"
});
this.addComponent("LocationBias", {
container: ".location-bias"
});
}
});
```
--------------------------------
### Get Connector Run Response Sample
Source: https://hitchhikers.yext.com/docs/managementapis/knowledgegraph/connectors
Example JSON response for retrieving connector run details. Includes status, timestamps, counts of created/updated/deleted/failed/unchanged items, and dry run results.
```json
{
"meta": {
"uuid": "4f72b877-e2d0-4de4-9324-b9cf2c03e1a0"
},
"response": {
"runUid": 0,
"status": "CREATED",
"runMode": "DEFAULT",
"triggerType": "AUTO",
"createdTimestamp": 0,
"completedTimestamp": 0,
"createdCount": 0,
"updatedCount": 0,
"deletedCount": 0,
"failedCount": 0,
"unchangedCount": 0,
"results": {
"createdCount": 0,
"updatedCount": 0,
"deletedCount": 0,
"failedCount": 0,
"unchangedCount": 0
},
"dryRunResults": {
"createdCount": 0,
"updatedCount": 0,
"deletedCount": 0,
"failedCount": 0,
"unchangedCount": 0
}
}
}
```
--------------------------------
### Basic FilterBox Configuration
Source: https://hitchhikers.yext.com/docs/search/filterbox-component
A basic example demonstrating how to configure the FilterBox component with static filter options and radius filters. Use this for a standard setup where filters are grouped and share common configurations.
```javascript
this.addComponent("FilterBox", {
container: ".filter-box-container",
searchOnChange: true,
filters: [
{
type: "FilterOptions",
control: "singleoption",
optionType: "STATIC_FILTER",
label: "Services",
options: [
{
label: "Pick Up",
field: "pickupAndDeliveryServices",
value: "In-Store Pickup"
},
{
label: "Delivery",
field: "pickupAndDeliveryServices",
value: "Delivery"
}
]
},
{
control: "singleoption",
type: "FilterOptions",
optionType: "RADIUS_FILTER",
showExpand: false,
label: "Within",
options: [
{
value: 8046.72,
label: "5 miles"
},
{
value: 16093.4,
label: "10 miles"
},
{
value: 40233.6,
label: "25 miles"
},
{
value: 80467.2,
label: "50 miles"
}
]
}
]
});
```
--------------------------------
### Create New Credentials Prompt
Source: https://hitchhikers.yext.com/docs/cli/getting-started/getting-started
When prompted during initialization, select 'Create new credentials' to set up a new Yext account connection.
```bash
? Please select one of the following options Create new credentials
```
--------------------------------
### Basic Initialization
Source: https://hitchhikers.yext.com/docs/search/initialization
Initializes the Answers JS library with the minimum required configuration options: apiKey, experienceKey, businessId, and experienceVersion. The `onReady` callback is used to add components after the library is loaded.
```APIDOC
## Basic Initialization
This is done using the **`ANSWERS.init`** command. This function accepts a set of configuration options.
At a minimum `apiKey`, `experienceKey`, `businessId` and `experienceVersion` must be specified. Here is an example:
```javascript
ANSWERS.init({
apiKey: "3517add824e992916861b76e456724d9",
experienceKey: "answers-js-docs",
businessId: "3215760",
experienceVersion: "PRODUCTION",
onReady: function() {
// ADD COMPONENTS HERE
},
});
```
The `onReady` property is used to add components. You can learn more about adding components in the Components section.
```
--------------------------------
### Example API Request for Content Endpoint
Source: https://hitchhikers.yext.com/docs/streams/knowledge-graph-source
This GET request demonstrates how to query the Content Endpoint for healthcare providers based on accepted insurance and treated conditions. Replace {api_key} with your actual API key.
```HTTP
GET https://cdn.yextapis.com/v2/accounts/me/api/providerEndpoint?api_key={api_key}&v=20200408&c_insurancesAccepted.name=Worlds%20Best%20Insurance&c_conditionsTreated.name=Rheumatoid%20Arthritis
```
--------------------------------
### Example Request to Fetch Reviews by Region
Source: https://hitchhikers.yext.com/docs/streams/reviews-source
Demonstrates a GET request to the 'reviewsByState' Content API endpoint to retrieve reviews for entities located in New York (NY). The filtering is done by passing the 'entity.address.region' query parameter.
```HTTP
GET https://cdn.yextapis.com/v2/accounts/me/api/reviewsByState?api_key={api_key}&v=20200408&entity.address.region=NY
```
--------------------------------
### Start Local Development Server
Source: https://hitchhikers.yext.com/docs/pages/super-quick-start
Connects to your Yext Knowledge Graph and starts a local development server with hot reloading. Supports dynamic mode by default to reflect Knowledge Graph changes. Use the --local flag to use only local data.
```bash
npm run dev
```
```bash
npm run dev --local
```
--------------------------------
### Dynamic Image Transformation Example
Source: https://hitchhikers.yext.com/docs/knowledge-graph/image-storing-and-serving?target=image-field-behavior
Demonstrates applying blur, crop, and rotation to a photo by modifying its hosted URL. This example shows the step-by-step process of transforming an image URL.
```text
https://a.mktgcdn.com/p/weDfOuuWD5IybzlazwEUUps4-NxElRV2E2O0_zOXE6U/1701x1295.jpg -> https://dyn.mktgcdn.com/p/weDfOuuWD5IybzlazwEUUps4-NxElRV2E2O0_zOXE6U/blur=20,height=1000,width=1000,fit=crop,rotate=90
```
--------------------------------
### Accounts: Get
Source: https://hitchhikers.yext.com/docs/managementapis/accountsettings/accounts
Get details for a specific account.
```APIDOC
## Accounts: Get
### Description
Get details for an account.
### Method
GET
### Endpoint
https://api.yextapis.com/v2/accounts/{accountId}
### Path Parameters
- **accountId** (string) - Required
### Query Parameters
- **v** (string) - Required - A date in `YYYYMMDD` format.
### Responses
#### Success Response (200)
Account Response
#### Response Example (200)
```json
{
"meta": {
"uuid": "4f72b877-e2d0-4de4-9324-b9cf2c03e1a0",
"errors": []
},
"response": {
"accountId": 1264805,
"locationCount": 11,
"subAccountCount": 0,
"accountName": "Yext Demo Account",
"contactFirstName": "John",
"contactLastName": "Doe",
"contactPhone": "1234567890",
"contactEmail": "johndoe@email.com"
}
}
```
#### Error Response (default)
Error Response
```