Skip to Content

lib/

The app/lib/ folder holds constants and helpers for one side only; .ts files run on the server, .tsx files run in the browser.

app/lib/ ├── password.ts # server: hash and compare passwords ├── query.ts # server: shared query helpers └── format.tsx # browser: display formatting

What it does

Helpers that belong to no single resource: validating a tax code, signing a payload, shared queries, display formatting. Any file name works under app/lib/, including list.ts or query.ts.

If both sides need it, put it in shared/ instead of keeping two copies.

Exports

Anything. Import as app/lib/<name>.

  • lib/<name>.ts: runs on the server. May import app/db, manh/env, hono.
  • lib/<name>.tsx: runs in the browser. May import react, antd, dayjs.

Example

app/lib/tax-code.ts
import { env } from "manh/env"; import { fail } from "manh/errors"; export function isTaxCode(v: string) { return /^\d{10}(-\d{3})?$/.test(v); } export async function lookupTaxCode(code: string) { if (!isTaxCode(code)) fail(400, "Invalid tax code", "BAD_TAX_CODE"); const res = await fetch(`https://api.tracuu.example.vn/v1/company/${code}`, { headers: { authorization: `Bearer ${env.TAX_API_KEY}` }, signal: AbortSignal.timeout(8000), }); if (!res.ok) fail(404, "Tax code not found", "NOT_FOUND"); return res.json(); }

Good to know

  • A lib/*.ts file used only by pages is renamed .tsx when written. It stays .ts when it imports a server module or a server file imports it.
  • The server never imports a browser file, and the reverse.
  • dayjs is for .tsx only. On the server use Date, Date.now() or ISO strings (code.no-dayjs-in-backend).
  • Read outside-service keys from env inside the function; never write them in code (code.hardcoded-secret).

Next steps

  • shared/ — where functions both pages and the server need go.
  • Call an outside API — keep the key in a secret and call fetch from the server.
Last updated