Server-only module referenced by client -- how to fix? #324
-
I'm following the docs' section on protected routes. An As I'm trying to move BE-only logic (e.g.
WORKSexport async function loader({request}: Route.LoaderArgs) {
let session = await sessionStorage.getSession(request.headers.get("cookie"))
let user = session.get("user")
... FAILSexport async function authenticate(request: Request) {
let session = await sessionStorage.getSession(request.headers.get("cookie"))
let user = session.get("user")
...
}
export async function loader({request}: Route.LoaderArgs) {
let user = await authenticate(request)
... I've never worked with Vite (trying to migrate from Next) previously, so I'm not sure if it's a bug or a gotcha with some fix available.
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I think I've found the solution myself. A helper touching the "BE" logic must not be exported from the module. |
Beta Was this translation helpful? Give feedback.
-
Always create those functions in a separate file, not in route files, route files contain route code only. And you can name the file
The compiler knows what exports from route are server-only (like a loader or action) and removes them when creating the client code, then it removes any unused code left after removing the server-only exports If you add that authenticate function in your route and export it, the bundler will leave it there because something may depend on it |
Beta Was this translation helpful? Give feedback.
Always create those functions in a separate file, not in route files, route files contain route code only.
And you can name the file
.server.ts
to tell the compiler it's a server-only moduleThe compiler knows what exports from route are server-only (like a loader or action) and removes them when creating the client code, then it removes any unused code left after removing the server-only exports
If you add that authenticate function in your route and export it, the bundler will leave it there because something may depend on it