Je hebt Javascript nodig om deze website te kunnen gebruiken. Pas je browserinstellingen in om verder te gaan!
Search

Authentication

Retrieve your Algolia token from Directus and choose a safe refresh strategy.

You need a valid API key to query Algolia. It is available on your Directus user account when you have the Algolia token policy.

Read algolia_token from your user profile after the policy is assigned. Its permissions mirror Directus: an indexed collection is searchable only when your account may read it in Directus.

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

const DIRECTUS_URL = "https://content.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 the token when needed

Algolia tokens are static. Permission changes in Directus take effect automatically in the 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.

On onderwijsloket.com, a server route fetches the token from Directus, caches it for seven days, and serves it to clients. Server initialisation fetches it asynchronously and passes it to the client.

When the page hydrates, it refreshes the token in the background and stores it in a cookie for ten minutes. It refreshes again after that cookie expires.

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

Keep in touch with the latest

Sign up for our monthly deep dives - straight to your inbox.