-
-
Notifications
You must be signed in to change notification settings - Fork 212
Description
Summary
While running the SvelteKit dev server (apps/web), I call auth.api.getSession from hooks.server.ts. The @project/auth package imports @project/db, which only reads from process.env without explicitly loading the env file. Because the SSR process runs with cwd = apps/web, dotenv only sees the frontend .env, so DATABASE_URL and DATABASE_AUTH_TOKEN remain empty. As a result, the database connection fails and the dev page returns HTTP 500.
Context
Monorepo Structure:
- Backend:
apps/server - Frontend (SvelteKit):
apps/web
Environment Variables:
- Backend credentials (
DATABASE_URL,DATABASE_AUTH_TOKEN, etc.) are stored inapps/server/.env apps/web/.envonly containsPUBLIC_*variables
hooks.server.ts
import { auth } from "@project/auth";
import type { Handle } from "@sveltejs/kit";
import { svelteKitHandler } from "better-auth/svelte-kit";
import { building } from "$app/environment";
export const handle: Handle = async ({ event, resolve }) => {
const session = await auth.api.getSession({
headers: event.request.headers,
});
if (session) {
event.locals.session = session.session;
event.locals.user = session.user;
}
return svelteKitHandler({ event, resolve, auth, building });
};Terminal Output
When running bun run dev inside apps/web:
Database URL: Not set
Database Auth Token: Not set
LibsqlError: URL_INVALID: The URL '' is not in a valid format
Error: Missing API key. Pass it to the constructor `new SomeService("key")`
Visiting http://localhost:5173 returns a 500 error.
Current Workaround
Add import "dotenv/config"; to packages/db/src/index.ts, then duplicate the backend credentials (DATABASE_URL, DATABASE_AUTH_TOKEN, etc.) into apps/web/.env.
Issue: Secrets are now duplicated across two env files.
Suggested Fix
Provide a shared helper so the auth/db packages always load the backend .env even when executed inside the frontend SSR process, or document that developers must keep the env variables in apps/server/.env and apps/web/.env in sync during development.