How to give each device its own credential on first boot: factory claim codes stored as hashes, a one-time provisioning call that cannot be replayed, device authentication on every later request, and revocation, on Postgres.

A device leaves the factory with a serial number and, at best, a code printed on the box. The backend has to turn that into a credential that belongs to one device, so that a leaked secret from one unit does not give access to the other ten thousand.
Fleet platforms solve this with claim credentials. AWS IoT fleet provisioning, for example, lets devices be manufactured with a claim certificate that the service exchanges for a unique device certificate on first connection. This guide builds the same shape as a small API you own, for fleets that talk HTTPS rather than MQTT.
The provisioning call must work exactly once per device even when two requests arrive together, and nothing in the database should be usable as a credential if it leaks, which is why both the claim code and the device secret are stored as hashes.
Do the claim as a single UPDATE ... WHERE provisioned_at IS NULL ... RETURNING. The database applies the update to one row for the first request and finds no matching row for any request after it, so there is no check-then-write gap to race through. If the update returns nothing, the device was already provisioned, revoked or given the wrong claim code, and the API answers all three the same way, so a caller cannot probe which serials exist.
Generate the device secret with a cryptographically secure source. Per the Node.js crypto documentation, crypto.randomBytes produces cryptographically strong random data, and crypto.createHash and crypto.timingSafeEqual cover hashing and comparing without leaking timing. A 32-byte random secret needs no slow password hash, since it is not a human-chosen password and cannot be guessed, so SHA-256 is enough for storing it.
Encore is a backend framework with built-in infrastructure, so the device table, the endpoints and the authentication are declared in one service. Per the GCP infrastructure docs and the AWS infrastructure docs, the deploy provisions Postgres in your own account, and encore run starts Postgres locally for the same code.

Run in your terminal to get started locally.
The registration endpoint for the factory, the one-time provisioning call, an authenticated heartbeat and the operator reset:
// devices/devices.ts
import { api, APIError, Gateway, Header } from "encore.dev/api";
import { authHandler } from "encore.dev/auth";
import { getAuthData } from "~encore/auth";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
const db = new SQLDatabase("devices", { migrations: "./migrations" });
const sha256 = (value: string) => createHash("sha256").update(value).digest("hex");
interface RegisterRequest {
devices: { serial: string; model: string; claimCode: string }[];
}
// Called by a factory or admin service in the same app, never by a device.
export const register = api(
{ expose: false, method: "POST", path: "/devices/register" },
async ({ devices }: RegisterRequest): Promise<{ registered: number }> => {
let registered = 0;
for (const d of devices) {
const r = await db.queryRow<{ serial: string }>`
INSERT INTO devices (serial, model, claim_code_hash)
VALUES (${d.serial}, ${d.model}, ${sha256(d.claimCode)})
ON CONFLICT (serial) DO NOTHING RETURNING serial`;
if (r) registered++;
}
return { registered };
},
);
// First boot: the first valid request gets a secret, every later one finds nothing to update.
export const provision = api(
{ expose: true, method: "POST", path: "/provision" },
async (req: { serial: string; claimCode: string }): Promise<{ deviceSecret: string }> => {
const secret = randomBytes(32).toString("base64url");
const row = await db.queryRow<{ serial: string }>`
UPDATE devices
SET secret_hash = ${sha256(secret)}, provisioned_at = now()
WHERE serial = ${req.serial}
AND claim_code_hash = ${sha256(req.claimCode)}
AND provisioned_at IS NULL AND revoked_at IS NULL
RETURNING serial`;
if (!row) throw APIError.permissionDenied("provisioning is not available for this device");
return { deviceSecret: secret };
},
);
interface AuthParams {
serial: Header<"X-Device-Serial">;
secret: Header<"X-Device-Secret">;
}
const auth = authHandler<AuthParams, { userID: string; serial: string }>(async (p) => {
const row = await db.queryRow<{ secret_hash: string }>`
SELECT secret_hash FROM devices
WHERE serial = ${p.serial ?? ""} AND secret_hash IS NOT NULL AND revoked_at IS NULL`;
const supplied = Buffer.from(sha256(p.secret ?? ""));
const stored = Buffer.from(row?.secret_hash ?? "");
if (!row || stored.length !== supplied.length || !timingSafeEqual(stored, supplied)) {
throw APIError.unauthenticated("invalid device credentials");
}
return { userID: p.serial, serial: p.serial };
});
export const gateway = new Gateway({ authHandler: auth });
export const heartbeat = api(
{ expose: true, auth: true, method: "POST", path: "/heartbeat" },
async (): Promise<{ ok: boolean }> => {
await db.exec`UPDATE devices SET last_seen_at = now() WHERE serial = ${getAuthData()!.serial}`;
return { ok: true };
},
);
// Operator tools: a device that lost its provisioning response, or one that was stolen.
export const reset = api(
{ expose: false, method: "POST", path: "/devices/:serial/reset" },
async ({ serial }: { serial: string }): Promise<{ reset: boolean }> => {
const r = await db.queryRow<{ serial: string }>`
UPDATE devices SET secret_hash = NULL, provisioned_at = NULL WHERE serial = ${serial} RETURNING serial`;
return { reset: r !== null };
},
);
export const revoke = api(
{ expose: false, method: "POST", path: "/devices/:serial/revoke" },
async ({ serial }: { serial: string }): Promise<{ revoked: boolean }> => {
const r = await db.queryRow<{ serial: string }>`
UPDATE devices SET revoked_at = now() WHERE serial = ${serial} RETURNING serial`;
return { revoked: r !== null };
},
);
-- devices/migrations/1_init.up.sql
CREATE TABLE devices (
serial TEXT PRIMARY KEY,
model TEXT NOT NULL,
claim_code_hash TEXT NOT NULL,
secret_hash TEXT,
provisioned_at TIMESTAMPTZ,
revoked_at TIMESTAMPTZ,
last_seen_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
The three internal endpoints use expose: false, so only other services in the app can call them, such as a factory or admin service that sits behind your own login, and the auth handler runs for every endpoint marked auth: true, as described in the auth docs. A reset clears the hash and the provisioning timestamp, which is the only way back after a lost response, and it should be an operator-only action with an audit trail. Locally, encore run starts Postgres, so the whole flow can be tested with curl before a deploy.
To deploy, connect your AWS or GCP account as described in Connect your cloud account and push with git push encore.
A coding agent asked to add certificate rotation changes the schema and the auth handler in one pull request and runs the flow locally, with no cloud setup in the way.
Best fit: Hardware teams that want a provisioning and device authentication API they own, with claim codes and secrets stored as hashes in a database in their own cloud account.
Provision the same device twice and confirm the second call is refused. Provision with a wrong claim code and a revoked serial and confirm all refusals look identical, then call heartbeat with a good and a bad secret and confirm only the good one passes.
Provisioning is the step where a device that left the factory with only a serial number or a shared claim credential receives its own unique credential, usually on first boot. After it, the backend can identify the device, authenticate its requests and revoke it individually.
Make the claim a single atomic update that only matches a device that has not been provisioned, so the first valid request wins and every later one finds nothing to update. The secret is returned in that one response and only its hash is stored.
The backend cannot show the secret again, because it only stored a hash. An authorised operator resets the device record, which clears the hash and lets the device run provisioning once more with its claim code.
With Encore you declare the SQLDatabase, the auth handler and the endpoints in the service, and the deploy provisions Postgres in your own AWS or GCP account, with encore run starting Postgres locally.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.