Access secret versions with @google-cloud/secret-manager, cache values, choose between latest and pinned versions, mount secrets on Cloud Run instead, grant the right IAM role, and see how declared secrets in TypeScript compare.

Google Secret Manager stores API keys and passwords for apps on GCP, and a Node.js service reads them with the @google-cloud/secret-manager client. One call returns the value, but resource names, byte payloads, version pinning, per-request latency and the secretAccessor grant decide whether it works after deploy.
This guide covers reading, caching, versions, Cloud Run mounting and IAM with version 8 of the client.
Create one client per process. It uses Application Default Credentials, which on Cloud Run or GKE means the runtime service account and on a laptop means your gcloud auth application-default login session. The helper caches values for five minutes:
import { SecretManagerServiceClient } from "@google-cloud/secret-manager";
const client = new SecretManagerServiceClient(); // one client per process, uses ADC
const project = process.env.GOOGLE_CLOUD_PROJECT ?? "acme-prod";
type Cached = { value: string; fetchedAt: number };
const cache = new Map<string, Cached>();
const TTL_MS = 5 * 60 * 1000;
export async function getSecret(name: string, version = "latest"): Promise<string> {
const key = `${name}@${version}`;
const hit = cache.get(key);
if (hit && Date.now() - hit.fetchedAt < TTL_MS) return hit.value;
const [res] = await client.accessSecretVersion({
name: `projects/${project}/secrets/${name}/versions/${version}`,
});
const data = res.payload?.data;
if (!data) throw new Error(`secret ${name} has no payload`);
const value = typeof data === "string" ? data : Buffer.from(data).toString("utf8");
cache.set(key, { value, fetchedAt: Date.now() });
return value;
}
A missing secret or version fails with gRPC code 5 (NOT_FOUND), a disabled version with code 9 (FAILED_PRECONDITION), and a missing grant with code 7 (PERMISSION_DENIED). The accessSecretVersion reference also returns a CRC32C checksum in payload.dataCrc32c, which Google's samples verify to detect corruption in transit.
latest is an alias for the newest enabled version. Reading it at runtime means a rotation applies within one cache TTL, without a deploy, while a pinned number such as versions/3 changes only when you change the code or configuration. Google's best practices recommend pinning versions in production deployments so that a bad new value does not roll out to every instance at once, and the trade-off is that rotation becomes a deploy step.
Cloud Run can expose a secret as an environment variable or a mounted file, so the app never calls the API:
An environment variable is resolved when the instance starts and keeps that value for the instance's lifetime, which is why pinned versions fit it. A mounted file referencing latest is read from Secret Manager when the app reads the file, so new versions reach running instances. Either way, the Cloud Run service account needs the accessor role on the secret.
Grant roles/secretmanager.secretAccessor to the runtime service account on each secret it reads:
A project-level grant works too, but gives the service every secret in the project, including other services' database passwords.
Secret Manager has no official emulator. The usual setups are a development project read with your own credentials, or a wrapper that falls back to process.env when NODE_ENV is development. The cache above also makes unit tests easy to stub, since getSecret is the only function that touches the client.
Encore brings infrastructure from code, and a secret is declared in TypeScript by name while its values are set per environment outside the repository. On GCP the values live in Secret Manager in your project and are injected into the service's containers, so there is no client, resource name or cache in the code.

Run in your terminal to get started locally.
// billing/billing.ts
import { api, APIError } from "encore.dev/api";
import { secret } from "encore.dev/config";
// Declared in code, valued per environment with `encore secret set`.
const stripeKey = secret("StripeKey");
interface RefundRequest {
paymentIntent: string;
}
interface RefundResponse {
refundId: string;
}
export const refund = api(
{ expose: true, method: "POST", path: "/refunds" },
async ({ paymentIntent }: RefundRequest): Promise<RefundResponse> => {
const resp = await fetch("https://api.stripe.com/v1/refunds", {
method: "POST",
headers: { Authorization: `Bearer ${stripeKey()}` },
body: new URLSearchParams({ payment_intent: paymentIntent }),
});
if (!resp.ok) {
throw APIError.unavailable(`stripe returned ${resp.status}`);
}
const body = (await resp.json()) as { id: string };
return { refundId: body.id };
},
);
The service also needs an encore.service.ts file in billing/. Values are set once per environment type, and encore run uses the local one, with a .secrets.local.cue file available for overrides that only apply on your machine:
On deploy to your own GCP project, Encore stores the values in Secret Manager and injects them as environment variables, as the GCP infrastructure docs describe, and Encore provisions an IAM role for the service, a service account on GCP. A deploy fails if a secret has no value for that environment, which catches the missing value before traffic does.
Secret values are not stored in the repository, so a coding agent can add secret("ResendKey") next to the code that needs it and run the service under encore run, while production values stay out of its context and out of git history.
Best fit: Services on GCP that want each secret declared next to the code using it and valued per environment in their own project.
Install @google-cloud/secret-manager, create a SecretManagerServiceClient, and call accessSecretVersion({ name: "projects/PROJECT/secrets/NAME/versions/latest" }). The value is in payload.data as bytes, so convert it with Buffer.from(data).toString("utf8").
Pin a version number when the value is injected at startup, such as Cloud Run environment variables, so a new version only takes effect with a deliberate deploy. Read latest at runtime when the code fetches the secret itself and you want rotation to apply without a deploy, and handle the old value failing in between.
roles/secretmanager.secretAccessor, granted to the runtime service account on the specific secret rather than the whole project. The Secret Manager Viewer role only shows metadata, because reading a payload needs the secretmanager.versions.access permission.
Either authenticate with gcloud auth application-default login and read the actual secret from a development project, or fall back to an environment variable locally. Encore handles this with a local value per secret, set with encore secret set --type local and supplied by encore run.
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.