Authentication

Learn how to request and refresh your Algolia token.

To query the Algolia instance, you must use a valid API key. This key is available in your Directus user account if you have been assigned the appropriate policy.

Once your account includes the Algolia Token policy, you can read the algolia_token field from your user profile. The permissions associated with this token mirror your Directus permissions. Any collection that is readable through Directus can also be queried in Algolia, provided the collection is indexed.

import { ofetch } from 'ofetch';
import { liteClient } from 'algoliasearch/lite'

const DIRECTUS_URL = 'https://api.v2.onderwijsloket.com';
const DIRECTUS_API_TOKEN = 'your_static_api_token_here';
const ALGOLIA_APP_ID = 'WSV9PQ4NXW';


// Fetch the Algolia token from Directus
const { data } = await ofetch<{ data: { algolia_token: string | null } }>(
    `${DIRECTUS_URL}/users/me`,
    {
        headers: {
            Authorization: `Bearer ${DIRECTUS_API_TOKEN}`,
        },
        query: {
            fields: [`algolia_token`],
        },
    },
)

// Initialize the Algolia client with the fetched token
const { algolia_token } = data;
const client = liteClient(ALGOLIA_APP_ID, algolia_token);

Refresh strategy (optional)

Algolia tokens are static. If your Directus permissions change, those updates are reflected automatically in your existing token.

Tokens only change if access to the search engine is revoked and later restored. This should be rare but can occur due to human error. You may implement a safeguard for this scenario.

Example refresh strategy

On onderwijsloket.com, a server route fetches the token from Directus, caches it for seven days, and serves it to clients. When the Algolia client initializes on the server, this endpoint is called asynchronously and the returned token is passed into the client. The resulting page is then aggressively cached so subsequent requests are served directly from HTML without re-rendering (and without refetching the token).

When the page hydrates on the client, the token is refreshed in the background and stored in a cookie with a 10-minute expiration. After the cookie expires, the token refreshes again.

If the Algolia client receives a 403 response, it fetches a fresh token immediately, bypassing the server-side cache.