Where the connection lives
Where the connection lives in the Databases guide.
Four rules cover every client:
- A
.servermodule owns the connection. A file whose name ends in.server.tscan never be bundled for the browser; the build fails with the import chain if a client module reaches it (see Keep secrets out of the browser). The connection string and the token are read there fromprocess.env, and nowhere else. - One client per process. A client opened per request exhausts the database's connections under load. Open it once at
module load. In
dusk devthe server module is reloaded when a file changes, which would open a second client each time, so the client is kept onglobalThisand reused. - Callers get functions, not the client. Loaders and API routes call server functions or functions of a
src/servermodule. The browser's build replaces a server function by a stub, so the query code never ships. - The schema is changed by migrations, run at deploy time by the migration tool of the library, not by the app on start. The example below creates its table in code only so that the page is self-contained.