aymeric-giraudet / svelte-algolia-instantsearch

A Svelte component library for Algolia InstantSearch.js
https://svelte-algolia-instantsearch.vercel.app/
MIT License
50 stars 12 forks source link

How to set API_KEY and APP_ID via env variable evaluated at runtime #33

Open jonathan-macke opened 10 months ago

jonathan-macke commented 10 months ago

Hi, I don't like the idea to have my API_KEY and APP_ID hardcoded in my application, even if I'm doing pure SSR. I'm trying to find a solution to "inject" those information into my component.

I have tried to customize the getServerState function. But when copy / paste as it is the getServerState function into my application, it generates an error Cannot subscribe to 'page' store on the server outside of a Svelte component, as it is bound to the current request via component context.

Here is my page.server.ts used in the sampe app provided by svelte-algolia-instantsearch.

import Page from "./+page.svelte";
//import { getServerState } from "$lib";
import type { PageServerLoad } from "./$types";
import type { InstantSearch } from "instantsearch.js";
import { getInitialResults, waitForResults } from "instantsearch.js/es/lib/server";

const serverContext = Symbol("InstantSearch:serverContext");

export const load: PageServerLoad = ({ url }) => getServerState(Page, url);

function getServerState(component: any, serverUrl: URL): Promise<Record<string, any>> {
    return new Promise((resolve) => {
      const notifyServer = async (search: InstantSearch) => {
        await waitForResults(search);
        const results = getInitialResults(search.mainIndex);
        search.dispose();
        resolve(results);
      };
      component.render({}, { context: new Map([[serverContext, { notifyServer, serverUrl }]]) });
    });
  }

May I know if you have an idea about how to solve this ?

jonathan-macke commented 10 months ago

I have proposed a solution in my PR: https://github.com/aymeric-giraudet/svelte-algolia-instantsearch/pull/34