PageSourceSearch

https://backstage.io/assets/js/7ffc8fd5.faab7fcc.js

js backstage.io collected 2026-09-24 08:29:36 UTC 33,719 bytes, 1 lines download raw bytes

1"use strict";(self.webpackChunkbackstage_microsite=self.webpackChunkbackstage_microsite||[]).push([["17659"],{699058(e,t,n){n.r(t),n.d(t,{assets:()=>l,contentTitle:()=>i,default:()=>d,frontMatter:()=>o,metadata:()=>a,toc:()=>c});var a=n(738801),s=n(474848),r=n(28453);let o={id:"integrating-search-into-plugins",title:"Integrating Search into a plugin",description:"How to integrate Search into a Backstage plugin"},i,l={},c=[{value:"Providing data to the search platform",id:"providing-data-to-the-search-platform",level:2},{value:"Create a collator",id:"create-a-collator",level:3},{value:"1. Create a collator module package",id:"1-create-a-collator-module-package",level:4},{value:"2. Install the collator dependencies",id:"2-install-the-collator-dependencies",level:4},{value:"3. Use Backstage App configuration",id:"3-use-backstage-app-configuration",level:4},{value:"4. Define the collator document type",id:"4-define-the-collator-document-type",level:4},{value:"5. Implement the collator factory",id:"5-implement-the-collator-factory",level:4},{value:"6. Implement the collator plugin module",id:"6-implement-the-collator-plugin-module",level:4},{value:"7. Install the collator module",id:"7-install-the-collator-module",level:4},{value:"8. Testing the collator code",id:"8-testing-the-collator-code",level:4},{value:"9. Running the collator locally",id:"9-running-the-collator-locally",level:4},{value:"10. Make your plugins collator discoverable for others",id:"10-make-your-plugins-collator-discoverable-for-others",level:4},{value:"Building a search experience into your plugin",id:"building-a-search-experience-into-your-plugin",level:2},{value:"Search Experience Concepts",id:"search-experience-concepts",level:3},{value:"Search Experience Tutorials",id:"search-experience-tutorials",level:3},{value:"Improved "404" page experience",id:"improved-404-page-experience",level:4},{value:"Simple search page",id:"simple-search-page",level:4},{value:"Custom search control surfaces",id:"custom-search-control-surfaces",level:4},{value:"Custom search results",id:"custom-search-results",level:4}];function h(e){let t={a:"a",admonition:"admonition",blockquote:"blockquote",code:"code",em:"em",h2:"h2",h3:"h3",h4:"h4",li:"li",ol:"ol",p:"p",pre:"pre",strong:"strong",ul:"ul",...(0,r.R)(),...e.components};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(t.admonition,{title:"Legacy Documentation",type:"caution",children:(0,s.jsx)(t.p,{children:"This section is part of the legacy plugins documentation. The backend search collator patterns described here use the new backend system and are still current. The frontend search experience examples use the old frontend system APIs."})}),"\n",(0,s.jsx)(t.p,{children:"The Backstage Search Platform was designed to give plugin developers the APIs\nand interfaces needed to offer search experiences within their plugins, while\nabstracting away (and instead empowering application integrators to choose) the\nspecific underlying search technologies."}),"\n",(0,s.jsx)(t.p,{children:"On this page, you'll find concepts and tutorials for leveraging the Backstage\nSearch Platform in your plugin."}),"\n",(0,s.jsx)(t.h2,{id:"providing-data-to-the-search-platform",children:"Providing data to the search platform"}),"\n",(0,s.jsx)(t.h3,{id:"create-a-collator",children:"Create a collator"}),"\n",(0,s.jsxs)(t.blockquote,{children:["\n",(0,s.jsxs)(t.p,{children:["Knowing what a ",(0,s.jsx)(t.a,{href:"/docs/features/search/concepts#collators",children:"collator"})," is will help you as you build it out."]}),"\n"]}),"\n",(0,s.jsxs)(t.p,{children:["Imagine you have a plugin that is responsible for storing FAQ snippets in a database. You want other engineers to be able to easily find your questions and answers. So that means you want them to be indexed by the search platform. Lets say the FAQ snippets can be viewed at a URL like ",(0,s.jsx)(t.code,{children:"backstage.example.biz/faq-snippets"}),"."]}),"\n",(0,s.jsxs)(t.p,{children:["The search platform provides an interface (",(0,s.jsx)(t.code,{children:"DocumentCollatorFactory"})," from package ",(0,s.jsx)(t.code,{children:"@backstage/plugin-search-common"}),') that allows you to do exactly that. It works by registering each of your entries as a "document" that later represents one search result each.']}),"\n",(0,s.jsxs)(t.blockquote,{children:["\n",(0,s.jsxs)(t.p,{children:["You can always look at a working example, e.g. ",(0,s.jsx)(t.a,{href:"https://github.com/backstage/backstage/blob/master/plugins/search-backend-module-stack-overflow-collator/src/collators/StackOverflowQuestionsCollatorFactory.ts",children:"StackOverflowQuestionsCollatorFactory"}),", if you are unsure or want to follow best practices."]}),"\n"]}),"\n",(0,s.jsx)(t.h4,{id:"1-create-a-collator-module-package",children:"1. Create a collator module package"}),"\n",(0,s.jsxs)(t.p,{children:["In order to add an FAQ collator to the Backstage index registry we have to create a ",(0,s.jsx)(t.a,{href:"https://backstage.io/docs/backend-system/building-plugins-and-modules/index#modules",children:"plugin module"}),", and the best way to do this is to create it in a separate package, e.g., ",(0,s.jsx)(t.code,{children:"plugins/search-backend-module-faq-snippets-collator"}),", using the ",(0,s.jsx)(t.code,{children:"yarn new"})," command:"]}),"\n",(0,s.jsxs)(t.ol,{children:["\n",(0,s.jsxs)(t.li,{children:["Access your Backstage project root directory and run ",(0,s.jsx)(t.code,{children:"yarn new"}),";"]}),"\n",(0,s.jsxs)(t.li,{children:["When asked about what do you want to create, please select ",(0,s.jsx)(t.code,{children:"backend-module"})," and hit enter;"]}),"\n",(0,s.jsxs)(t.li,{children:["Input ",(0,s.jsx)(t.code,{children:"search"})," as the plugin ID and ",(0,s.jsx)(t.code,{children:"faq-snippets-collator"})," as the module ID;"]}),"\n",(0,s.jsxs)(t.li,{children:["A ",(0,s.jsx)(t.code,{children:"search-backend-module-faq-snippets-collator"}),' folder should have been created in your project\'s "plugins" directory.']}),"\n"]}),"\n",(0,s.jsx)(t.h4,{id:"2-install-the-collator-dependencies",children:"2. Install the collator dependencies"}),"\n",(0,s.jsx)(t.p,{children:"We will use some libraries in the module, so let's add them to your plugin module dependencies:"}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-sh",children:"# Create a new branch using Git command-line\ngit checkout -b tutorials/new-faq-snippets-collator\n\n# Install the package containing the interface\nyarn workspace @internal/backstage-plugin-search-backend-module-faq-snippets-collator add @backstage/plugin-search-common @backstage/plugin-search-backend-node\n"})}),"\n",(0,s.jsx)(t.h4,{id:"3-use-backstage-app-configuration",children:"3. Use Backstage App configuration"}),"\n",(0,s.jsxs)(t.p,{children:["Your new collator could benefit from using configuration directly from the Backstage ",(0,s.jsx)(t.code,{children:"app-config.yaml"})," file which is located on the project's root folder:"]}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-yaml",children:"faq:\n  baseUrl: https://backstage.example.biz/faq-snippets\n"})}),"\n",(0,s.jsxs)(t.p,{children:["It is optional to define a schedule for the collator to run, or else it defaults to the value in the collator factory code (See ",(0,s.jsx)(t.a,{href:"#5-implement-the-collator-factory",children:"5. Implement the collator factory"}),"):"]}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-yaml",children:'faq:\n  baseUrl: https://backstage.example.biz/faq-snippets\n  /* highlight-add-start */\n  schedule:\n    # supports cron, ISO duration, "human duration" as used in code\n    frequency: { minutes: 30 }\n    # supports ISO duration, "human duration" as used in code\n    timeout: { minutes: 3 }\n  /* highlight-add-end */\n'})}),"\n",(0,s.jsx)(t.h4,{id:"4-define-the-collator-document-type",children:"4. Define the collator document type"}),"\n",(0,s.jsxs)(t.p,{children:["Before we can start generating documents from our FAQ entries, we first have to define a document type containing all necessary information we need to later display our entry as 
1search result. The package ",(0,s.jsx)(t.code,{children:"@backstage/plugin-search-common"})," we installed earlier contains a type ",(0,s.jsx)(t.code,{children:"IndexableDocument"})," that we can extend."]}),"\n",(0,s.jsxs)(t.p,{children:["Create a new file ",(0,s.jsx)(t.code,{children:"plugins/search-backend-module-faq-snippets-collator/src/types.ts"})," and paste the following below:"]}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-ts",children:"import { IndexableDocument } from '@backstage/plugin-search-common';\n\nexport interface FaqSnippetDocument extends IndexableDocument {\n  answered_by: string;\n}\n"})}),"\n",(0,s.jsx)(t.h4,{id:"5-implement-the-collator-factory",children:"5. Implement the collator factory"}),"\n",(0,s.jsxs)(t.p,{children:["Imagine your FAQs can be retrieved at the URL ",(0,s.jsx)(t.code,{children:"https://backstage.example.biz/faq-snippets"})," with following JSON response format:"]}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-json",children:'{\n  "items": [\n    {\n      "id": 42,\n      "question": "What is The Answer to the Ultimate Question of Life, the Universe, and Everything?",\n      "answer": "Forty-two",\n      "user": "Deep Thought"\n    }\n  ]\n}\n'})}),"\n",(0,s.jsxs)(t.p,{children:["Below we provide an example implementation of how the FAQ collator factory could look like using our new document type, placed in the ",(0,s.jsx)(t.code,{children:"plugins/search-backend-module-faq-snippets-collator/src/factory.ts"})," file:"]}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-ts",children:"import { Readable } from 'stream';\nimport {\n  LoggerService,\n  RootConfigService,\n} from '@backstage/backend-plugin-api';\nimport { DocumentCollatorFactory } from '@backstage/plugin-search-common';\nimport { FaqSnippetDocument } from './types';\n\nconst DEFAULT_BASE_URL = 'https://backstage.example.biz/faq-snippets';\n\nexport class FaqSnippetsCollatorFactory implements DocumentCollatorFactory {\n  public readonly type: string = 'faq-snippets';\n  private readonly baseUrl: string;\n  private readonly logger: LoggerService;\n\n  private constructor(options: { logger: LoggerService; baseUrl: string }) {\n    this.baseUrl = options.baseUrl;\n    this.logger = options.logger;\n  }\n\n  static fromConfig(\n    config: RootConfigService,\n    options: {\n      logger: LoggerService;\n    },\n  ) {\n    const baseUrl = config.getOptionalString('faq.baseUrl') ?? DEFAULT_BASE_URL;\n    return new FaqSnippetsCollatorFactory({ ...options, baseUrl });\n  }\n\n  async getCollator() {\n    return Readable.from(this.execute());\n  }\n\n  async *execute(): AsyncGenerator<FaqSnippetDocument> {\n    this.logger.info(`Fetching faq snippets from ${this.baseUrl}`);\n    const response = await fetch(this.baseUrl);\n    const data = await response.json();\n    for (const faq of data.items) {\n      yield {\n        title: faq.question,\n        location: `/faq-snippets/${faq.id}`,\n        text: faq.answer,\n        answered_by: faq.user,\n      };\n    }\n  }\n}\n"})}),"\n",(0,s.jsx)(t.h4,{id:"6-implement-the-collator-plugin-module",children:"6. Implement the collator plugin module"}),"\n",(0,s.jsxs)(t.p,{children:["Now we have to connect the search backend plugin with our FAQ Snippets collator factory, so replace the ",(0,s.jsx)(t.code,{children:"module.ts"})," file with the content below:"]}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-ts",metastring:"title='plugins/search-backend-module-faq-snippets-collator/src/module.ts'",children:"import {\n  coreServices,\n  createBackendModule,\n  readSchedulerServiceTaskScheduleDefinitionFromConfig,\n} from '@backstage/backend-plugin-api';\nimport { searchIndexRegistryExtensionPoint } from '@backstage/plugin-search-backend-node/alpha';\nimport { FaqSnippetsCollatorFactory } from './factory';\n\nexport const searchFaqSnippetsCollatorModule = createBackendModule({\n  pluginId: 'search',\n  moduleId: 'faq-snippets-collator',\n  register(env) {\n    env.registerInit({\n      deps: {\n        config: coreServices.rootConfig,\n        logger: coreServices.logger,\n        scheduler: coreServices.scheduler,\n        indexRegistry: searchIndexRegistryExtensionPoint,\n      },\n      async init({ config, logger, scheduler, indexRegistry }
1) {\n        const defaultSchedule = {\n          frequency: { minutes: 10 },\n          timeout: { minutes: 15 },\n          initialDelay: { seconds: 3 },\n        };\n\n        const schedule = config.has('faq.schedule')\n          ? readSchedulerServiceTaskScheduleDefinitionFromConfig(\n              config.getConfig('faq.schedule'),\n            )\n          : defaultSchedule;\n\n        indexRegistry.addCollator({\n          schedule: scheduler.createScheduledTaskRunner(schedule),\n          factory: FaqSnippetsCollatorFactory.fromConfig(config, { logger }),\n        });\n      },\n    });\n  },\n});\n"})}),"\n",(0,s.jsxs)(t.p,{children:["In the fragment above, the module is registered, and when the Backstage backend initializes it, it adds the FAQ Snippets collator to the search index registry. Now let's export the module as default from the ",(0,s.jsx)(t.code,{children:"index.ts"})," file:"]}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-ts",metastring:"title='plugins/search-backend-module-faq-snippets-collator/src/index.ts'",children:"export { searchFaqSnippetsCollatorModule as default } from './module';\n"})}),"\n",(0,s.jsx)(t.h4,{id:"7-install-the-collator-module",children:"7. Install the collator module"}),"\n",(0,s.jsx)(t.p,{children:"The newly created module should be added to the backend package dependencies as follows:"}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-sh",children:"yarn --cwd packages/backend add @internal/backstage-plugin-search-backend-module-faq-snippets-collator\n"})}),"\n",(0,s.jsx)(t.p,{children:"After that, install the module on your Backstage backend instance:"}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-ts",metastring:"title='packages/backend/src/index.ts'",children:"import { createBackend } from '@backstage/backend-defaults';\n//...\nconst backend = createBackend();\n// Installing the search backend plugin\nbackend.add(import('@backstage/plugin-search-backend'));\n// Installing the newly created faq snippets collator module\nbackend.add(\n  import(\n    '@internal/backstage-plugin-search-backend-module-faq-snippets-collator'\n  ),\n);\n//...\nbackend.start();\n"})}),"\n",(0,s.jsx)(t.h4,{id:"8-testing-the-collator-code",children:"8. Testing the collator code"}),"\n",(0,s.jsxs)(t.p,{children:["To verify your implementation works as expected make sure to add tests for it. For your convenience, there is the ",(0,s.jsx)(t.a,{href:"https://backstage.io/api/stable/classes/_backstage_plugin-search-backend-node.index.TestPipeline.html",children:(0,s.jsx)(t.code,{children:"TestPipeline"})})," utility that emulates a pipeline into which you can integrate your custom collator."]}),"\n",(0,s.jsxs)(t.p,{children:["Look at ",(0,s.jsx)(t.a,{href:"https://github.com/backstage/backstage/blob/de294ce5c410c9eb56da6870a1fab795268f60e3/plugins/techdocs-backend/src/search/DefaultTechDocsCollatorFactory.test.ts",children:"DefaultTechDocsCollatorFactory test"}),", for an example."]}),"\n",(0,s.jsxs)(t.p,{children:["You can also check out the documentation on ",(0,s.jsx)(t.a,{href:"/docs/backend-system/building-plugins-and-modules/testing",children:"how to test Backstage plugin modules"}),"."]}),"\n",(0,s.jsx)(t.h4,{id:"9-running-the-collator-locally",children:"9. Running the collator locally"}),"\n",(0,s.jsxs)(t.p,{children:["Run ",(0,s.jsx)(t.code,{children:"yarn start"})," in the root folder of your Backstage project and look for logs like these:"]}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-sh",children:'[backend]: YYYY-MM-DDTHH:MM:SS.000Z search info Registered scheduled task: search_index_faq_snippets, {"version":2,"cadence":"PT10M","initialDelayDuration":"PT3S","timeoutAfterDuration":"PT15M"} task=search_index_faq_snippets\n[backend]: YYYY-MM-DDTHH:MM:SS.000Z search info Collating documents for faq-snippets via FaqSnippetsCollatorFactory documentType=faq-snippets\n[backend]: YYYY-MM-DDTHH:MM:SS.000Z search info Fetching faq snippets from https://backstage.example.biz/faq-snippets\n[backend]: YYYY-MM-DDTHH:MM:SS.000Z search info Collating documents for faq-snippets succeeded documentType=faq-snippets\n'})}),"\n",(0,s.jsxs)(t.p,{children:["It means that the collator task was started and completed successfully. Visit ",(0,s.jsx)(t.a,{href:"http://localhost:3000",children:"http://localhost:3000"}),", log in, select the 'All' tab, and type in one of your snippets title in the search box."]}),"\n",(0,s.jsx)(t.p,{children:"Results should appear for snippets."}),"\n",(0,s.jsx)(t.h4,{id:"10-make-your-plugins-collator-discoverable-for-others",children:"10. Make your plugins collator discoverable for others"}),"\n",(0,s.jsxs)(t.p,{children:["If you want to make your collator discoverable for other adopters, add it to the list of ",(0,s.jsx)(t.a,{href:"https://backstage.io/docs/features/search/#plugins-integrated-with-backstage-search",children:"plugins integrated to search"}),"."]}),"\n",(0,s.jsx)(t.h2,{id:"building-a-search-experience-into-your-plugin",children:"Building a search experience into your plugin"}),"\n",(0,s.jsxs)(t.p,{children:["While the core Search plugin offers components and extensions that empower app\nintegrators to compose a global search experience, you may find that you want a\nnarrower search experience just within your plugin. This could be as literal as\nan autocomplete-style search bar focused on documents provided by your plugin\n(for example, the ",(0,s.jsx)(t.a,{href:"https://github.com/backstage/backstage/blob/master/plugins/techdocs/src/search/components/TechDocsSearch.tsx",children:"TechDocsSearch"}),"\ncomponent), or as abstract as a widget that presents a list of links that\nare contextually related to something else on the page."]}),"\n",(0,s.jsx)(t.h3,{id:"search-experience-concepts",children:"Search Experience Concepts"}),"\n",(0,s.jsx)(t.p,{children:"Knowing these high-level concepts will help you as you craft your in-plugin\nsearch experience."}),"\n",(0,s.jsxs)(t.ul,{children:["\n",(0,s.jsxs)(t.li,{children:["All search experiences must be wrapped in a ",(0,s.jsx)(t.code,{children:"<SearchContextProvider>"}),", which\nis provided by ",(0,s.jsx)(t.code,{children:"@backstage/plugin-search-react"}),". This context keeps track\nof state necessary to perform search queries and display any results. As\ninputs to the query are updated (e.g. a ",(0,s.jsx)(t.code,{children:"term"})," or ",(0,s.jsx)(t.code,{children:"filter"})," values), the\nupdated query is executed and ",(0,s.jsx)(t.code,{children:"results"})," are refreshed. Check out the\n",(0,s.jsx)(t.a,{href:"https://backstage.io/api/stable/types/_backstage_plugin-search-react.index.SearchContextValue.html",children:"SearchContextValue"}),"\nfor details."]}),"\n",(0,s.jsxs)(t.li,{children:["The aforementioned state can be modified and/or consumed via the\n",(0,s.jsx)(t.code,{children:"useSearch()"})," hook, also exported by ",(0,s.jsx)(t.code,{children:"@backstage/plugin-search-react"}),"."]}),"\n",(0,s.jsxs)(t.li,{children:["For more literal search experiences, reusable components are available\nto import and compose into a cohesive experience in your plugin (e.g.\n",(0,s.jsx)(t.code,{children:"<SearchBar />"})," or ",(0,s.jsx)(t.code,{children:"<SearchFilter.Checkbox />"}),"). You can see all such\ncomponents in ",(0,s.jsx)(t.a,{href:"https://backstage.io/storybook/?path=/story/plugins-search-searchbar--default",children:"Backstage's storybook"}),"."]}),"\n"]}),"\n",(0,s.jsx)(t.h3,{id:"search-experience-tutorials",children:"Search Experience Tutorials"}),"\n",(0,s.jsx)(t.p,{children:"The following tutorials make use of packages and plugins that you may 
1not yet\nhave as dependencies for your plugin; be sure to add them before you use them!"}),"\n",(0,s.jsxs)(t.ul,{children:["\n",(0,s.jsxs)(t.li,{children:[(0,s.jsx)(t.a,{href:"https://www.npmjs.com/package/@backstage/plugin-search-react",children:(0,s.jsx)(t.code,{children:"@backstage/plugin-search-react"})})," - A\npackage containing components, hooks, and types that are shared across all\nfrontend plugins, including plugins like yours!"]}),"\n",(0,s.jsxs)(t.li,{children:[(0,s.jsx)(t.a,{href:"https://www.npmjs.com/package/@backstage/plugin-search",children:(0,s.jsx)(t.code,{children:"@backstage/plugin-search"})})," - The\nmain search plugin, used by app integrators to compose global search\nexperiences. "]}),"\n",(0,s.jsxs)(t.li,{children:[(0,s.jsx)(t.a,{href:"https://www.npmjs.com/package/@backstage/core-components",children:(0,s.jsx)(t.code,{children:"@backstage/core-components"})})," - A\npackage containing generic components useful for a variety of experiences\nbuilt in Backstage."]}),"\n"]}),"\n",(0,s.jsx)(t.h4,{id:"improved-404-page-experience",children:'Improved "404" page experience'}),"\n",(0,s.jsxs)(t.p,{children:["Imagine you have a plugin that allows users to manage ",(0,s.jsx)(t.em,{children:"widgets"}),". Perhaps they\ncan be viewed at a URL like ",(0,s.jsx)(t.code,{children:"backstage.example.biz/widgets/{widgetName}"}),".\nAt some point, a widget is renamed, and links to that widget's page from\nchat systems, wikis, or browser bookmarks become stale, resulting in errors or\n404s."]}),"\n",(0,s.jsx)(t.p,{children:'What if instead of showing a broken page or the generic "looks like someone\ndropped the mic" 404 page, you showed a list of possibly related widgets?'}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-javascript",children:"import { Link } from '@backstage/core-components';\nimport { SearchResult } from '@backstage/plugin-search';\nimport { SearchContextProvider } from '@backstage/plugin-search-react';\n\nexport const Widget404Page = ({ widgetName }) => {\n  // Supplying this to <SearchContextProvider> runs a pre-filtered search with\n  // the given widgetName as the search term, focused on search result of type\n  // \"widget\" with no other filters.\n  const preFiltered = {\n    term: widgetName,\n    types: ['widget'],\n    filters: {},\n  };\n\n  return (\n    <SearchContextProvider initialState={preFiltered}>\n      {/* The <SearchResult> component allows us to iterate through results and\n          display them in whatever way fits best! */}\n      <SearchResult>\n        {({ results }) => (\n          {results.map(({ document }) => (\n            <Link to={document.location} key={document.location}>\n              {document.title}\n            </Link>\n          ))}\n        )}\n      <SearchResult>\n    </SearchContextProvider>\n  );\n);\n"})}),"\n",(0,s.jsx)(t.p,{children:"Not all search experiences require user input! As you can see, it's possible to\nleverage the Backstage Search Platform's frontend framework without necessarily\ngiving users input controls."}),"\n",(0,s.jsx)(t.h4,{id:"simple-search-page",children:"Simple search page"}),"\n",(0,s.jsxs)(t.p,{children:["Of course, it's also possible to provide a more fully featured search\nexperience in your plugin. The simplest way is to leverage reusable components\nprovided by the ",(0,s.jsx)(t.code,{children:"@backstage/plugin-search"})," package, like this:"]}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-javascript",children:"import { useProfile } from '@internal/api';\nimport {\n  Content,\n  ContentHeader,\n  PageWithHeader,\n} from '@backstage/core-components';\nimport { SearchBar, SearchResult } from '@backstage/plugin-search';\nimport { SearchContextProvider } from '@backstage/plugin-search-react';\n\nexport const ManageMyWidgets = () => {\n  const { primaryTeam } = useProfile();\n  // In this example, note how we are pre-filtering results down to a specific\n  // owner field value (the currently logged-in user's team), but allowing the\n  // search term to be controlled by the user via the <SearchBar /> component.\n  const preFiltered = {\n    types: ['widget'],\n    term: '',\n    filters: {\n      owner: primaryTeam,\n    },\n  };\n\n  return (\n    <PageWithHeader title=\"Widgets Home\">\n      <Content>\n        <ContentHeader title=\"All your Widgets and More\" />\n        <SearchContextProvider initialState={preFiltered}>\n          <SearchBar />\n          <SearchResult>\n            {/* Render results here, just like above */}\n          </SearchResult>\n        </SearchContextProvider>\n      </Content>\n    </PageWithHeader>\n  );\n};\n"})}),"\n",(0,s.jsx)(t.h4,{id:"custom-search-control-surfaces",children:"Custom search control surfaces"}),"\n",(0,s.jsxs)(t.p,{children:["If the reusable search components provided by ",(0,s.jsx)(t.code,{children:"@backstage/plugin-search"})," aren't\nadequate, no problem! There's an API in place that you can use to author your\nown components to control the various parts of the search context."]}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-javascript",children:"import { use
1Search } from '@backstage/plugin-search-react';\nimport ChipInput from 'material-ui-chip-input';\n\nexport const CustomChipFilter = ({ name }) => {\n  const { filters, setFilters } = useSearch();\n  const chipValues = filters[name] || [];\n\n  // When a chip value is changed, update the filters value by calling the\n  // setFilters function from the search context.\n  const handleChipChange = (chip, index) => {\n    // There may be filters set for other fields. Be sure to maintain them.\n    setFilters(prevState => {\n      const { [name]: filter = [], ...others } = prevState;\n\n      if (index === undefined) {\n        filter.push(chip);\n      } else {\n        filter.splice(index, 1);\n      }\n\n      return { ...others, [name]: filter };\n    });\n  };\n\n  return (\n    <ChipInput\n      value={chipValues}\n      onAdd={handleChipChange}\n      onDelete={handleChipChange}\n    />\n  );\n};\n"})}),"\n",(0,s.jsxs)(t.p,{children:["Check out the ",(0,s.jsx)(t.a,{href:"https://github.com/backstage/backstage/blob/master/plugins/search-react/src/context/SearchContext.tsx",children:"SearchContextValue type"}),"\nfor more details on what methods and values are available for manipulating and\nreading the search context."]}),"\n",(0,s.jsx)(t.p,{children:"If you produce something generic and reusable, consider contributing your\ncomponent upstream so that all users of the Backstage Search Platform can\nbenefit. Issues and pull requests welcome."}),"\n",(0,s.jsx)(t.h4,{id:"custom-search-results",children:"Custom search results"}),"\n",(0,s.jsxs)(t.p,{children:["Search results throughout Backstage are rendered as lists so that list items can easily be customized; although a ",(0,s.jsx)(t.a,{href:"https://backstage.io/storybook/?path=/story/plugins-search-defaultresultlistitem--default",children:"default result list item"})," is available, plugins are in the best position to provide custom result list items that surface relevant information only known to the plugin."]}),"\n",(0,s.jsxs)(t.p,{children:["The example below imagines ",(0,s.jsx)(t.code,{children:"YourCustomSearchResult"})," as a type of search result that contains associated ",(0,s.jsx)(t.code,{children:"tags"})," which could be rendered as chips below the title/text."]}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-tsx",children:"import { Link } from '@backstage/core-components';\nimport { useAnalytics } from '@backstage/core-plugin-api';\nimport { ResultHighlight } from '@backstage/plugin-search-common';\nimport { HighlightedSearchResultText } from '@backstage/plugin-search-react';\n\ntype CustomSearchResultListItemProps = {\n  result: YourCustomSearchResult;\n  rank?: number;\n  highlight?: ResultHighlight;\n};\n\nexport const CustomSearchResultListItem = (\n  props: CustomSearchResultListItemProps,\n) => {\n  const { title, text, location, tags } = props.result;\n\n  const analytics = useAnalytics();\n  const handleClick = () => {\n    analytics.captureEvent('discover', title, {\n      attributes: { to: location },\n      value: props.rank,\n    });\n  };\n\n  return (\n    <Link noTrack to={location} onClick={handleClick}>\n      <ListItem alignItems=\"center\">\n        <Box flexWrap=\"wrap\">\n          <ListItemText\n            primaryTypographyProps={{ variant: 'h6' }}\n            primary={\n              highlight?.fields?.title ? (\n                <HighlightedSearchResultText\n                  text={highlight.fields.title}\n                  preTag={highlight.preTag}\n                  postTag={highlight.postTag}\n                />\n              ) : (\n                title\n              )\n            }\n            secondary={\n              highlight?.fields?.text ? (\n                <HighlightedSearchResultText\n                  text={highlight.fields.text}\n                  preTag={highlight.preTag}\n                  postTag={highlight.postTag}\n                />\n              ) : (\n                text\n              )\n            }\n          />\n          {tags &&\n            tags.map((tag: string) => (\n              <Chip key={tag} label={`Tag: ${tag}`} size=\"small\" />\n            ))}\n        </Box>\n      </ListItem>\n      <Divider />\n    </Link>\n  );\n};\n"})}),"\n",(0,s.jsxs)(t.p,{children:["The optional use of the ",(0,s.jsx)(t.code,{children:"<HighlightedSearchResultText>"})," component makes it possible to highlight relevant parts of the result based on the user's search query."]}),"\n",(0,s.jsxs)(t.p,{children:[(0,s.jsx)(t.strong,{children:"Note on Analytics"}),": In order for app integrators to track and improve search experiences across Backstage, it's important for them to understand when and what users search for, as well as what they click on after searching. When providing a custom result component, it's your responsibility as a plugin developer to instrument it according to search analytics conventions. In particular:"]}),"\n",(0,s.jsxs)(t.ul,{children:["\n",(0,s.jsxs)(t.li,{children:["You must use the ",(0,s.jsx)(t.code,{children:"analytics.captureEvent"})," method, from the ",(0,s.jsx)(t.code,{children:"useAnalytics()"})," hook (detailed ",(0,s.jsx)(t.a,{href:"/docs/plugins/analytics",children:"plugin analytics docs are here"}),")."]}),"\n",(0,s.jsxs)(t.li,{children:["You must ensure that the action of the event, representing a click on a search result item, is ",(0,s.jsx)(t.code,{children:"discover"}),", and the subject is the ",(0,s.jsx)(t.code,{children:"title"})," of the clicked result. In addition, the ",(0,s.jsx)(t.code,{children:"to"})," attribute should be set to the result's ",(0,s.jsx)(t.code,{children:"location"}),", and the ",(0,s.jsx)(t.code,{children:"value"})," of the event must be set to the ",(0,s.jsx)(t.code,{children:"rank"})," (passed in as a prop)."]}),"\n",(0,s.jsxs)(t.li,{children:["You must ensure that the aforementioned ",(0,s.jsx)(t.code,{children:"captureEvent"})," method is called when a user clicks the link; you should further ensure that the ",(0,s.jsx)(t.code,{children:"noTrack"})," prop is added to the link (which disables default link click tracking, in favor of this custom instrumentation)."]}),"\n"]}),"\n",(0,s.jsxs)(t.p,{children:["For other examples and inspiration on custom result list items, check out the ",(0,s.jsx)(t.a,{href:"https://github.com/backstage/backstage/blob/c981e83/plugins/stack-overflow/src/search/StackOverflowSearchResultListItem/StackOverflowSearchResultListItem.tsx",children:(0,s.jsx)(t.code,{children:"<StackOverflowSearchResultListItem>"})})," or ",(0,s.jsx)(t.a,{href:"https://github.com/backstage/backstage/blob/c981e83/plugins/catalog/src/components/CatalogSearchResultListItem/CatalogSearchResultListItem.tsx",children:(0,s.jsx)(t.code,{children:"<CatalogSearchResultListItem>"})})," components."]})]})}function d(e={}){let{wrapper:t}={...(0,r.R)(),...e.components};return t?(0,s.jsx)(t,{...e,children:(0,s.jsx)(h,{...e})}):h(e)}},28453(e,t,n){n.d(t,{R:()=>o,x:()=>i});var a=n(296540);let s={},r=a.createContext(s);function o(e){let t=a.useContext(r);return a.useMemo(function(){return"function"==typeof e?e(t):{...t,...e}},[t,e])}function i(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(s):e.components||s:o(e.components),a.createElement(r.Provider,{value:t},e.children)}},738801(e){e.exports=JSON.parse('{"id":"plugins/integrating-search-into-plugins","title":"Integrating Search into a plugin","description":"How to integrate Search into a Backstage plugin","source":"@site/versioned_docs/version-stable/plugins/integrating-search-into-plugins.md","sourceDirName":"plugins","slug":"/plugins/integrating-search-into-plugins","permalink":"/docs/plugins/integrating-search-into-plugins","draft":false,"unlisted":false,"editUrl":"https://github.com/backstage/backstage/edit/master/docs/plugins/integrating-search-into-plugins.md","tags":[],"version":"stable","frontMatter":{"id":"integrating-search-into-plugins","title":"Integrating Search into a plugin","description":"How to integrate Search into a Backstage plugin"},"sidebar":"docs","previous":{"title":"Integrate into the Software Catalog","permalink":"/docs/plugins/integrating-plugin-into-software-catalog"},"next":{"title":"Composability System","permalink":"/docs/plugins/composability"}}')}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.