Keeping the API Key on the Server in Next.js
One file talks to the CMS, and it refuses to be bundled for the browser. That is the whole trick.
Two kinds of keys
Onttle has publishable keys (pk-proj_), which are read-only and safe in a browser, and secret keys (sk-proj_), which can write and run searches. This blog uses BM25 search, a POST request, so it needs a secret key.
One module, server only
Every API call lives in src/lib/onttle.ts. The first line is:
import "server-only";
If a client component ever imports this file, the build fails. That is better than discovering the key in a network tab.
Rules I follow
- No
NEXT_PUBLIC_prefix on anything secret - Error messages contain a status code and a path, never a response body
- The search form submits with
GETto a server component; the browser never calls the CMS