[]previous and next page

Where the connection lives

Where the connection lives in the Databases guide.

For agentsUpdated

Four rules cover every client:

  1. A .server module owns the connection. A file whose name ends in .server.ts can 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 from process.env, and nowhere else.
  2. One client per process. A client opened per request exhausts the database's connections under load. Open it once at module load. In dusk dev the server module is reloaded when a file changes, which would open a second client each time, so the client is kept on globalThis and reused.
  3. Callers get functions, not the client. Loaders and API routes call server functions or functions of a src/server module. The browser's build replaces a server function by a stub, so the query code never ships.
  4. 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.