T
TanStack7mo ago
extended-salmon

Ensure server-only code remains server-only

having a bit of trouble understanding how "server only" code stays "server only" in TSS. i assume this dynamic import is an anti pattern:
export const listOrganizations = async () => {
const auth = await import("@/lib/server/auth").then((mod) => mod.auth);
const req = getWebRequest();
if (!req) {
throw new Error("No request found");
}
const orgs = await auth.api.listOrganizations({ headers: req.headers });
return orgs;
};
export const listOrganizations = async () => {
const auth = await import("@/lib/server/auth").then((mod) => mod.auth);
const req = getWebRequest();
if (!req) {
throw new Error("No request found");
}
const orgs = await auth.api.listOrganizations({ headers: req.headers });
return orgs;
};
i'm not sure how i'd use that function in a beforeLoad otherwise, eg
import { listOrganizations } from "@/lib/orgs";

export const Route = createFileRoute("/(app)/_app")({
component: RouteComponent,
beforeLoad: async ({ context }) => {
if (!context.user) {
throw redirect({
to: "/signin",
});
}
const orgs = await listOrganizations()
console.log(`orgs: ${JSON.stringify(orgs)}`)
},
});
import { listOrganizations } from "@/lib/orgs";

export const Route = createFileRoute("/(app)/_app")({
component: RouteComponent,
beforeLoad: async ({ context }) => {
if (!context.user) {
throw redirect({
to: "/signin",
});
}
const orgs = await listOrganizations()
console.log(`orgs: ${JSON.stringify(orgs)}`)
},
});
any help is much appreciated!
3 Replies
extended-salmon
extended-salmonOP7mo ago
for context @/lib/server/auth imports postgres. that is causing the client to crash, of course
rising-crimson
rising-crimson7mo ago
you need to use createServerFn to isolate the code
xenial-black
xenial-black7mo ago
loaders are isomorphic so you'd have to wrap listOrganizations in a server function https://tanstack.com/start/latest/docs/framework/react/server-functions
Server Functions | TanStack Start React Docs
What are Server Functions? Server functions allow you to specify logic that can be invoked almost anywhere (even the client), but run only on the server. In fact, they are not so different from an API...

Did you find this page helpful?