Typesense.org

Integrate Typesense.org with Strapi

Typesense.org logo

Why Use Typesense?

Typesense is an open-source, typo-tolerant search engine that makes your applications smarter. Integrating Typesense with Strapi enhances search functionality by improving the speed and relevance of search results. This integration allows developers to use Typesense's fast, typo-tolerant search engine to create powerful search experiences in Strapi-powered applications. Enhanced search capabilities can improve user engagement and satisfaction, indirectly supporting SEO efforts. Additionally, Strapi's flexibility in content management and its compatibility with modern frontend frameworks enable the creation of SEO-friendly websites.

Setting up Typesense and integrating it with Strapi takes minutes. If you're in the process of choosing a headless CMS, Strapi's seamless integration with tools like Typesense is a significant advantage. You'll spend less time configuring and more time watching your users enjoy professional search experiences. Want all the details? Check out the official documentation.

Why Use Strapi?

Strapi is the leading open-source headless CMS offering features, like customizable APIs, role-based permissions, multilingual support, etc. It simplifies content management and integrates effortlessly with modern frontend frameworks.

Explore the Strapi documentation for more details.

Strapi 5 Highlights

The out-of-the-box Strapi features allow you to get up and running in no time:

  1. Single types: Create one-off pages that have a unique content structure.
  2. Draft and Publish: Reduce the risk of publishing errors and streamline collaboration.
  3. 100% TypeScript Support: Enjoy type safety & easy maintainability
  4. Customizable API: With Strapi, you can just hop in your code editor and edit the code to fit your API to your needs.
  5. Integrations: Strapi supports integrations with Cloudinary, SendGrid, Algolia, and others.
  6. Editor interface: The editor allows you to pull in dynamic blocks of content.
  7. Authentication: Secure and authorize access to your API with JWT or providers.
  8. RBAC: Help maximize operational efficiency, reduce dev team support work, and safeguard against unauthorized access or configuration modifications.
  9. i18n: Manage content in multiple languages. Easily query the different locales through the API.
  10. Plugins: Customize and extend Strapi using plugins.

Learn more about Strapi 5 feature.

Setup Strapi 5 Headless CMS

We are going to start by setting up our Strapi 5 project with the following command:

πŸ–οΈ Note: make sure that you have created a new directory for your project.

You can find the full documentation for Strapi 5 here.

Install Strapi

npx create-strapi-app@latest server

You will be asked to choose if you would like to use Strapi Cloud we will choose to skip for now.

 Strapi   v5.6.0 πŸš€ Let's create your new project

To deploy your project, create a new project on the Strapi Cloud dashboard.

? Please log in or sign up. 
  Login/Sign up 
❯ Skip 

After that, you will be asked how you would like to set up your project. We will choose the following options:

? Do you want to use the default database (sqlite) ? Yes
? Start with an example structure & data? Yes <-- make sure you say yes 
? Start with Typescript? Yes
? Install dependencies with npm? Yes
? Initialize a git repository? Yes

Once everything is set up and all the dependencies are installed, you can start your Strapi server with the following command:

cd server
npm run develop

You will be greeted with the Admin Create Account screen.

003-strapi-5.png

Go ahead and create your first Strapi user. All of this is local so you can use whatever you want.

Once you have created your user, you will be redirected to the Strapi Dashboard screen.

004-strapi-5.png

Publish Article Entries

Since we created our app with the example data, you should be able to navigate to your Article collection and see the data that was created for us.

005-strapi-5.png

Now, let's make sure that all of the data is published. If not, you can select all items via the checkbox and then click the Publish button.

Strapi Articles Published

Enable API Access

Once all your articles are published, we will expose our Strapi API for the Articles Collection. This can be done in Settings -> Users & Permissions plugin -> Roles -> Public -> Article.

You should have find and findOne selected. If not, go ahead and select them.

007-strapi-5.png

Test API

Now, if we make a GET request to http://localhost:1337/api/articles, we should see the following data for our articles.

008-strapi-5.png

πŸ–οΈ Note: The article covers (images) are not returned. This is because the REST API by default does not populate any relations, media fields, components, or dynamic zones.. Learn more about REST API: Population & Field Selection.

So, let's get the article covers by using the populate=* parameter: http://localhost:1337/api/articles?populate=*

vuejs strapi integration - api request.png

Getting Started with Typesense

Adding Typesense to Strapi supercharges your app's search capabilities. Here's how to set it up. If you're new to headless CMS migration, integrating these tools can seem daunting, but we'll guide you through the process. Understanding the importance of API integration is crucial; for more, see understanding API connections.

Configuring Strapi Environment for Typesense Integration

Add these environment variables to your .env file to set up the connection:

TYPESENSE_HOST=localhost
TYPESENSE_PORT=8108
TYPESENSE_PROTOCOL=http
TYPESENSE_API_KEY=xyz
TYPESENSE_CONNECTION_TIMEOUT_SECONDS=2

These configurations aim to connect your Strapi app to your Typesense server. Using a hosted Typesense service? Just adjust the values accordingly.

Installing and Adjusting Settings

Install the Typesense JavaScript client:

npm install typesense
# or
yarn add typesense

If you're familiar with JavaScript frameworks for developers, installing the Typesense client will be straightforward.

Create a config file at config/typesense.js:

module.exports = ({ env }) => ({
  connection: {
    nodes: [
      {
        host: env('TYPESENSE_HOST', 'localhost'),
        port: env('TYPESENSE_PORT', '8108'),
        protocol: env('TYPESENSE_PROTOCOL', 'http')
      }
    ],
    apiKey: env('TYPESENSE_API_KEY', 'xyz'),
    connectionTimeoutSeconds: env('TYPESENSE_CONNECTION_TIMEOUT_SECONDS', 2)
  }
});

This configuration file allows you to set specific Typesense settings for your Strapi application, which can be accessed throughout the app when properly referenced in the code.

Code Implementation for Integration

Next, create the Typesense client and your first collection schema. Add this service file at src/services/typesense.js:

const Typesense = require('typesense');

module.exports = () => ({
  client: null,
  
  initialize() {
    const config = strapi.config.get('typesense.connection');
    this.client = new Typesense.Client(config);
    return this;
  },
  
  async createCollection(schema) {
    try {
      return await this.client.collections().create(schema);
    } catch (error) {
      if (error.httpStatus === 409) {
        // Collection already exists
        return this.client.collections(schema.name).retrieve();
      }
      throw error;
    }
  },
  
  async indexDocument(collectionName, document) {
    return await this.client.collections(collectionName).documents().create(document);
  }
});

By leveraging this integration, Strapi for frontend developers becomes even more powerful, allowing you to build dynamic, search-optimized applications. You can further enhance Strapi's functionality by integrating with Typesense, opening up new possibilities for your projects. For more ideas on how to expand your development, check out these API project ideas.

The setup involves initializing a service in Strapi by modifying src/index.js. The code provided aims to initialize a Typesense service and create a collection for articles, specifying fields such as 'id', 'title', 'content', 'publishedAt', 'author', and 'categories'. This setup is intended to activate the Typesense connection upon Strapi's startup and manage the articles collection.

module.exports = {
  register(/* { strapi } */) {},
  
  async bootstrap({ strapi }) {
    // Initialize Typesense service
    strapi.service('api::typesense.typesense').initialize();
    
    // Create a collection for articles
    const articlesSchema = {
      name: 'articles',
      fields: [
        { name: 'id', type: 'string' },
        { name: 'title', type: 'string' },
        { name: 'content', type: 'string' },
        { name: 'publishedAt', type: 'int64' },
        { name: 'author', type: 'string' },
        { name: 'categories', type: 'string[]' }
      ]
    };
    
    await strapi.service('api::typesense.typesense').createCollection(articlesSchema);
  },
};

You can now start indexing your Strapi content and build powerful search features using the Typesense RESTful API. Understanding the evolution of APIs can help you make the most of these tools. For further enhancing Strapi functionality, integrating with Typesense opens up new possibilities.

Strapi Open Office Hours

If you have any questions about Strapi 5 or just would like to stop by and say hi, you can join us at Strapi's Discord Open Office Hours Monday through Friday at 12:30 pm - 1:30 pm CST: Strapi Discord Open Office Hours

For more details, visit the Strapi documentation and Typesense documentation.

Frequently Asked Questions

Typesense is a typo-tolerant search engine that provides fast, relevant search results. Integrate it with Strapi to enable powerful search functionality across your content with features like faceted search and geographic queries.

Use Strapi's lifecycle hooks to index content in Typesense when entries are created, updated, or deleted. Configure which fields to index and set up collection schemas matching your content structure.

Yes, Typesense runs as a separate service. Use Typesense Cloud for managed hosting or self-host using Docker. Configure your Strapi application with the Typesense server URL and API key.

Typesense offers typo tolerance, faceted filtering, geographic search, synonyms, and relevance tuning. These features enable sophisticated search experiences beyond Strapi's built-in filtering capabilities.

Use InstantSearch.js or framework-specific libraries (React InstantSearch) to build search interfaces. Query Typesense directly from your frontend for real-time search results.