typescriptsvelteprismasveltekit

Doing call to prisma client from load function in Svelte Kit


I'm using Prisma.io to write a database and would like to call the Prisma client from a typescript function.

I tried to use the load function of Svelte kit and also writing the call in a hidden _api.ts file but it didn't work. The Prisma client is complaining that it cannot be run from the browser. I understand it should somehow be run only on the server. What is the proper way to use Prisma with Svelte kit and run calls on the server?


Solution

  • The "load" function in Svelte may run on the server or in the browser, so this is probably the cause of the error.

    I suggest you turn the _api.ts into a callable endpoint. You then need to make sure that the api.ts exports a function named 'get' (or other methd). More info here: https://kit.svelte.dev/docs#routing-endpoints

    Once this is done, you should be able to browse to the api route directly, and you should see the outcome of your 'get' function in the api.ts file.

    Then, in your "load" function, you can use the 'fetch' method to access that route and grab the data. In Svelte, the fetch method works on both the server and the browser. https://kit.svelte.dev/docs#loading-input-fetch

    Update:

    To do 'POST' endpoints, you need to export a function called 'post' in your endpoint file. I suggest you console.log the request to see what you data you receive when the endpoint is called:

    export async function get(request) {
      console.log(request);
      return {
        body: { success: true },
      };
    }