Customize search functions
You may need to customize search behavior for scenarios such as:
- Processing search keywords, such as removing sensitive words.
- Filtering the default full-text search results.
- Reporting the search keywords.
- Customizing the search data source, such as searching from the database.
- Rendering custom search data sources.
Rspress provides interfaces for extending the default theme's search components so you can customize search behavior.
Understanding searchHooks
Use the search.searchHooks option in the Rspress config to register search component hooks:
The value of search.searchHooks is a file path. This file exports hook logic such as onSearch, allowing you to customize search at runtime. We call this file a searchHooks module.
Hook functions in searchHooks
The searchHooks module supports beforeSearch, onSearch, afterRender, and render.
In the searchHooks module, export only the hook functions you need.
beforeSearch
The beforeSearch hook runs before search starts. Use it to process or report search keywords.
This hook supports asynchronous operations.
Example:
onSearch
The onSearch hook runs after the default full-text search finishes. Use it to filter or report search results, or to add a custom search data source.
This hook supports asynchronous operations.
Example:
The onSearch hook returns an array of search source results. Each item has the following structure:
result is the search result and can have any structure you need. renderType controls how the result is rendered. When it is RenderType.Default, Rspress uses the default rendering logic. When it is RenderType.Custom, Rspress uses the render function.
afterSearch
The afterSearch hook runs after search results are rendered. Use it to access the final search keywords and results.
This hook supports asynchronous operations.
Example:
render
The render function will render the custom search source data in your onSearch hook. Therefore, it generally needs to be used together with onSearch. Here's how to use it:
The result is as follows:
