'Is there a way to run prisma in the sveltekit load function?

I have a sveltekit app I'm working on and it includes Prisma, I have been trying to pass a posts Array to all of my routes via the __layout's load function.
This error shows up when I load the site Prisma client error, PrismaClient is unable to be run in the browser

This is my code

<!-- src/routes/__layout.svelte -->
<script context=module>
    export const ssr = true;
    import Prisma from '$lib/db';
    // code breaks past this import, nothing runs, cant even test the code below
    import { browser } from '$app/env'; 
    export async function load() {
        let posts;
        let db = new Prisma();
        if(!browser) {
            posts = await db.post.findMany({
                select: {
                    id: true,
                    title: true,
                    body: true,
                    authorId: true,
                    author: true,
                }
            })

            await db.$disconnect();
        } else {
            posts = [
                {
                    id: 0,
                    title: 'An error ocurred',
                    body: '',
                    authorId: 0,
                    author: {}
                }
            ]
        }
        return {
            stuff: {
                posts
            }
        }
    }
</script>
// src/lib/db.ts
import Prisma, * as PrismaAll from "@prisma/client";

const PrismaClient = Prisma?.PrismaClient || PrismaAll?.PrismaClient;
const prisma = new PrimsaClient();
export default prisma;

Please tell me if I'm doing something wrong.



Solution 1:[1]

using hooks.ts as a workaround.

import db from "$lib/db"

/** @type {import('@sveltejs/kit').GetSession} */
export async function getSession() {
    let posts = await db.post.findMany({
        select: {
            id: true,
            title: true,
            body: true,
            authorId: true,
            author: true,
        }
    })
    db.$disconnect();
    return {
        posts
    }
}

and my load function looks like this

<script context=module>
    export async function load({ session }) {
        return {
            stuff: {
                ...session
            }
        }
    }
</script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1