SolidJSS
SolidJS2y ago
31 replies
florian

Split server code from client code

Hey, I am currently working on a project where I'm writing a good amount of server side logic which uses secrets for different things and database stuff which should stay on the server.

With solid-start I'm running into a lot of issues where it seems like vite or vinxi or whatever build tool wants to build my server side code for client side use.

For example when building my app it looks like it wants to build node builtins used by packages like mongodb and also my own logic for the browser. It doesn't really make any sense to me as I don't use any of that code inside components. I only use e.g. the mongodb package in a file which is just exporting a few wrapper functions for me to query data easier and those functions are only getting used inside server functions.

Seeing this makes me feel also kinda unsure if e.g. my secrets are secure and don't end up in client side code by accident. How can I make sure that this won't happen and how do I fix the build issues?

Here is a file from my codebase, this is also the only file where I use vinxi:
import {action, cache, redirect} from "@solidjs/router";
import {validate} from "email-validator";
import * as db from "../../../database.js";
import * as auth from "../../../auth.js";
import {deleteCookie, getCookie} from "vinxi/http";

export const signUp = action(async (formData) => {
    "use server";
    const email = formData.get("email");
    if (email && validate(email)) {
        const user = await db.getUserByEmail(email);
        if (user) {
            return new Error("Email address already in use.");
        } else {
            const code = auth.randomCode();
            // send email code
            const verifyState = auth.encryptPayload({email, code, intent: "signup"});
            return redirect(`/verify?state=${verifyState}`);
        }
    } else {
        return new Error("Invalid email address.");
    }
}, "sign-up");

export const checkSession = cache(async () => {
    "use server";
    const sessionCookie = getCookie("session");
    if (sessionCookie) {
        try {
            const sessionData = auth.decryptPayload(sessionCookie);
            if (sessionData.state === auth.SessionState.Authenticated && sessionData.userId) {
                const user = await db.getUserById(sessionData.userId);
                if (user) {
                    return redirect("/app");
                }
            }
            throw new Error();
        } catch {
            deleteCookie("session");
        }
    }
}, "check-session");
image.png
image.png
Was this page helpful?