| | |

Netlify 20 ๐ŸŒ Build Plugins, Observability & Governance โ€” Extending build lifecycles, monitoring logs/analytics, RBAC, and credit optimization

โฑ๏ธ Estimated read: 23 min | |

A Netlify site has three seats of control that the source repository cannot see. The first is the build lifecycle. Between the moment a deploy starts and the moment it goes live there are six named hooks, and a build plugin is the only supported way to attach logic to them โ€” to validate a file, to restore a cache, to inspect the output, or to refuse the deploy because a budget was exceeded. The second seat is observability. Build logs, function logs, and Analytics all record something about a production site, but they record different things at different levels of aggregation, and reading one of them as though it were the others leads to confident wrong conclusions. The third seat is governance โ€” who on the team can push a deploy button, which environment variables a branch deploy is allowed to read, and what a site is costing per month and per request.

These three belong in one chapter because they share a subject: the deploy, as an event that has an author, a duration, a cost, and a postmortem. A build plugin is how you act on that event. Observability is how you learn from it. Governance is how you bound it. A team that builds plugins without observability ships silent failures; a team that watches metrics without governance discovers the bandwidth spike after the invoice; a team with governance and no observability has rules nobody can verify.

This chapter walks the three in order. The first section covers the build plugin API โ€” the lifecycle events, the utils object, and the two cache modes. The second covers what Netlify records per deploy and per function, why server-side Analytics differs from a client-side analytics script, and how structured logging makes a function log searchable. The third covers roles, SAML, audit logs, and environment variable scoping as policy. The fourth collects the usage levers โ€” builds, bandwidth, functions, storage โ€” that keep the bill attributable.

Key point: A build plugin is the only sanctioned hook into the deploy lifecycle, onPreBuild through onEnd; Netlify’s observability stack records three different resolutions of truth โ€” build logs, function logs, and server-side Analytics โ€” and governance is the set of scopes and roles that decides who sees them and what a deploy is permitted to spend.


Why exists

The lifecycle gap. A framework build is a black box between “commit pushed” and “site deployed”. Teams want to run a check afterwards โ€” verify the sitemap exists, confirm no oversized images shipped, fail the deploy if the bundle grew by 30%. Netlify exposes named build events so this logic has a defined place to live and a defined failure semantic, rather than being smuggled into a postbuild npm script with no access to the build context.

The cold-cache cost. Every build that re-downloads dependencies and re-generates derived assets pays for the same work twice. Build plugins can persist a directory between deploys, so a build that would take four minutes with a cold dependency cache can take ninety seconds, and build minutes are a metered resource on every plan.

The invisible-failure problem. A function that starts returning 500s at 3am does not break the site โ€” the HTML still serves, the CDN is fine, and the first report comes from a customer. Function logs exist so that the error is discoverable before the report, and the reason they are structured rather than free-form is so that a specific level and route can be filtered out of tens of thousands of lines.

The ad-blocker distortion. Client-side analytics undercount. A meaningful fraction of browsers block the script, and the blocked cohort is not random โ€” it skews technical and privacy-conscious. Server-side Analytics exists because the CDN already saw the request, so no script, no consent banner interaction, and no undercount from blocking.

The audit problem. “Who deployed to production on Friday” is a question with a correct answer that must be retrievable. Without roles, SSO, and an audit log, the answer is a guess reconstructed from git commits that do not record the deploy action itself. Governance exists so the deploy has a recorded author and a permission check in front of it.

The runaway-spend problem. Usage on a serverless platform is elastic in both directions. A misconfigured image pipeline can move terabytes through the CDN, and a retry loop can invoke a function a million times overnight. Visibility into usage by site and by resource, plus the levers to reduce each one, is what keeps elasticity from becoming unpredictability.


a. Build plugins โ€” the six lifecycle events and the utils object

A build plugin is a module exporting functions named after build events. It is declared in netlify.toml under [[plugins]], either as a local path or a published package, and it may declare inputs that the plugin receives as a typed object.

The events fire in a fixed order. onPreBuild runs before the build command and is where validation and cache restoration belong, because a failure there costs seconds rather than minutes. onBuild runs after the build command produces output but before the deploy begins. onPostBuild runs after the deploy is created. onSuccess fires when everything succeeded and onError fires instead of it when anything failed. onEnd always runs last, whether the outcome was success or failure, which makes it the place for cleanup and for reporting that must happen either way.

// plugins/build-report/index.js
// Six hooks, but most plugins implement two or three of them.
export const onPreBuild = async ({ constants, utils }) => {
  // constants.CONTEXT is "production", "deploy-preview", "branch-deploy" or "dev"
  if (constants.CONTEXT === "deploy-preview") {
    // status.show renders a titled note in the deploy log
    utils.status.show({ title: "Preview build", summary: `branch ${constants.BRANCH}` });
  }
};

export const onPostBuild = async ({ constants, utils, inputs }) => {
  // utils.run.command executes a shell command and surfaces its output in the log
  const { stdout } = await utils.run.command("du -sk dist | cut -f1");
  const kilobytes = Number(stdout.trim());

  // failBuild stops the deploy; failPlugin marks only this plugin as failed
  if (kilobytes > inputs.maxKilobytes) {
    return utils.build.failBuild(
      `Output is ${kilobytes} KB, over the ${inputs.maxKilobytes} KB budget`
    );
  }
};

export const onEnd = async ({ constants, utils }) => {
  // Always runs, so an ingest call here reports both good and bad deploys
  await fetch(`${process.env.REPORT_ENDPOINT}/deploys`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ deploy: constants.DEPLOY_ID, context: constants.CONTEXT }),
  }).catch(() => {
    // A reporting failure must never turn a good deploy into a failed one
    utils.status.show({ title: "Report failed", summary: "ingest unreachable" });
  });
};

The distinction between failBuild and failPlugin is the one most plugins get wrong. failBuild cancels the deploy and the site keeps serving its previous version โ€” correct for a broken build, a missing sitemap, or a failed test suite. failPlugin records the plugin as failed but lets the deploy continue โ€” correct for a lint warning or a reporting hiccup where the artefact itself is fine.

Caching is the other half of the API. A plugin declares cache: "manual" and then saves and restores keys explicitly, or declares cache: "netlify" and receives the framework’s default cache directory without managing it.

// plugins/cache-content/index.js โ€” manual cache mode
export const onPreBuild = async ({ utils }) => {
  // Restoring returns the list of keys it found; a cold cache returns nothing
  const restored = await utils.cache.restore("generated-content");
  if (restored.length === 0) {
    utils.status.show({ title: "Cache", summary: "cold โ€” content will be regenerated" });
  }
};

export const onBuild = async ({ utils }) => {
  // Save the directory after the build produced it, so the next deploy reuses it
  await utils.cache.save("generated-content");
};

export const onEnd = async ({ utils }) => {
  // Every saved key, useful when a stale cache needs to be invalidated
  const keys = await utils.cache.list();
  utils.status.show({ title: "Cache keys", summary: keys.join(", ") || "none" });
};

The constants object is what makes a plugin context-aware without reading environment variables: CONTEXT, BRANCH, COMMIT_REF, CACHED_COMMIT_REF, DEPLOY_ID, SITE_ID, IS_LOCAL, PUBLISH_DIR and FUNCTIONS_SRC. The last of those is how a plugin behaves correctly under netlify dev, where IS_LOCAL is true and the network sandbox is different.


b. Observability โ€” three resolutions of the same deploy

Netlify records the deploy at three levels, and they answer different questions. The build log is one record per deploy and answers “did the build succeed, and where did it spend its time”. The function log is one record per invocation and answers “what happened during this specific request”. Analytics is an aggregate over server-side request data and answers “how much traffic arrived, from where, and which pages 404”.

Build logs are the coarse view. Every build is retrievable from the deploy list, the log is downloadable, and plugins contribute to it through utils.status.show, which is why a plugin that reports its own budget check makes the deploy log self-explanatory. Build logs are also where the deploy summary lives โ€” the duration, the context, the commit, and the cache hit or miss.

Function logs are the fine view, and they are only as useful as the log lines are structured. A function that writes console.log("error") produces a line that cannot be filtered by route, user, or severity. A function that writes one JSON object per event produces a log where level and route are fields.

// netlify/functions/checkout.js โ€” structured, one JSON object per line
export default async (req, context) => {
  const started = Date.now();

  // A single helper keeps every line in the same shape, so the log
  // can be filtered by level or route instead of grepped by phrase
  const log = (level, msg, extra = {}) =>
    console.log(
      JSON.stringify({
        level,
        msg,
        route: "checkout",
        country: context.geo?.country?.code,   // ISO country from the CDN edge
        ms: Date.now() - started,
        ...extra,
      })
    );

  try {
    const order = await req.json();
    log("info", "order received", { orderId: order.id });

    const result = await charge(order);
    log("info", "order charged", { orderId: order.id, amount: result.amount });
    return Response.json(result);
  } catch (err) {
    // The stack goes in the log, never in the response body
    log("error", "charge failed", { orderId: "unknown", stack: err.stack });
    return new Response("checkout failed", { status: 502 });
  }
};

Logs are streamed live in the Netlify UI per function, and the CLI is the faster path when a deploy is being debugged from a terminal. Deploy logs and function logs are separate commands, which reflects the separation in the UI.

# Tail the log of one function in real time
netlify logs:function checkout

# Fetch the build log for a specific deploy
netlify logs:deploy --deploy <deploy-id>

Analytics is the aggregate view and it is structurally different from the client-side scripts most teams have installed alongside it. It is computed server-side from CDN request logs, so it needs no snippet in the page, counts requests that a blocker would have suppressed, and cannot be defeated by JavaScript being disabled. The cost of that accuracy is granularity: there is no per-user journey and no event tracking โ€” you get page views, unique visitors, top pages, top sources, and 404s, over a rolling window of recent data rather than a full archive. The pairing that makes sense is Analytics for totals and a client-side tool for funnels, with the understanding that the two totals will never agree and that the gap is the blocked cohort, not a bug in either.

For functions, the modern layer above raw logs is distributed tracing. Netlify’s observability captures OpenTelemetry-compatible traces for functions, visible alongside invocations and errors in the Netlify UI and exportable to an external collector through the standard OTLP protocol, which means a span recorded in a function can be correlated with the rest of an organisation’s traces in whatever backend they already run. Adopting it requires no rewrite: the structured level and route fields described above become span attributes, and the function’s own started/ms timing is replaced by span durations measured by the platform.


c. Governance โ€” roles, SSO, audit, and variable scoping

Netlify teams have three built-in roles, and the distinction that matters is whether a member can trigger a production deploy. An Owner can do everything including billing and destructive site operations. A Developer can deploy, manage environment variables, and change settings. A Reviewer can read the site, view deploys and logs, and comment, without the ability to deploy or change configuration. Enterprise teams add SAML single sign-on through an identity provider such as Okta or Azure AD, directory sync via SCIM so that removing someone from the directory removes their Netlify access, custom roles, and an audit log that records who did what and when.

The audit log is the answer to the Friday-afternoon question, and it is worth knowing before you need it that it is an Enterprise capability rather than something available on every plan.

Environment variable scoping is the governance control that most affects day-to-day safety, and it has two independent axes. The first is deploy context: a variable can be defined globally and overridden per context, so a preview build can be given a sandbox API key while production receives the live one, with no code change and no conditional in the application.

# netlify.toml โ€” one variable, three contexts, same name
[context.production.environment]
  PAYMENTS_API_URL = "https://api.payments.example.com"

[context.deploy-preview.environment]
  # A preview that charged real cards would be the worst kind of surprise
  PAYMENTS_API_URL = "https://sandbox.payments.example.com"

[context.branch-deploy.environment]
  PAYMENTS_API_URL = "https://staging.payments.example.com"

The second axis is visibility. Variables marked as secret are write-only in the UI โ€” once saved they cannot be read back, only replaced โ€” which removes the habit of copying a production key into a chat message. Scope can also be restricted to build-time or runtime-only, so a key that only the build needs is not handed to every function invocation.

Deploy policy is the third lever. On Enterprise plans, branch deploys can be restricted to a defined set of branches, so a push to a personal branch does not produce a deploy and does not consume build minutes. Deploy keys and personal access tokens are the fourth: a CI pipeline should authenticate with a scoped deploy key belonging to the site, never with a human’s token, so revoking a person’s access does not silently break the pipeline.

# netlify.toml โ€” a repo-level rule is a governance rule
[build]
  # Skip the build entirely when nothing that affects the output changed.
  # This is the single largest build-minute saving available to most sites.
  ignore = "git diff --quiet $CACHED_COMMIT_REF $COMMIT_REF ."

[build.environment]
  # Pin the toolchain, or a silently-upgraded major version re-runs every build
  NODE_VERSION = "22"

Headers are the last governance surface worth naming, because cache policy is both a security decision and a cost decision. A static asset with a fingerprinted filename should be immutable for a year; an HTML page should be short-lived so a deploy is visible immediately. Getting that backwards produces either stale pages or a bandwidth bill.

[[headers]]
  for = "/assets/*"
  [headers.values]
    # Fingerprinted filenames make a long TTL safe and eliminate revalidation
    Cache-Control = "public, max-age=31536000, immutable"

[[headers]]
  for = "/*"
  [headers.values]
    # HSTS and a restrictive referrer policy are cheap and permanent wins
    Strict-Transport-Security = "max-age=31536000; includeSubDomains"
    Referrer-Policy = "strict-origin-when-cross-origin"

d. Usage and credit optimization โ€” where the meters actually move

Netlify’s plans meter a small set of resources: build minutes, bandwidth, function invocations and runtime, form submissions, and โ€” with the newer services โ€” Blobs operations and storage, database compute and storage, and AI Gateway tokens. Optimising is not a single trick, it is one lever per meter, applied in the order the meter is largest.

Builds. Three levers, in order of impact. Skipping the build entirely when nothing relevant changed, through the ignore command, is worth more than any other optimisation on a monorepo. Restoring a dependency cache, either through a plugin or through the platform’s default framework caching, removes the repeated install. Reducing the build’s own work โ€” avoiding a full re-render on every commit by using incremental builds where the framework supports them โ€” addresses what remains.

Bandwidth. Immutable caching on fingerprinted assets means a repeat visitor downloads nothing. Serving images through an image CDN at the size actually displayed avoids shipping a 4000-pixel photograph into a 320-pixel slot. Compressing text assets, and not shipping two copies of the same vendor bundle from two different routes, are the next two.

Functions. Invocation count and runtime both bill. Caching a function’s response at the edge with Netlify-CDN-Cache-Control converts a thousand invocations into one. Keeping the bundle small reduces cold-start duration, which is billed runtime. Moving latency-sensitive, stateless logic to an edge function avoids a regional round trip. And the most common accidental cost is a client-side poll: a setInterval fetching an unchanged endpoint every ten seconds is a thousand invocations per user per day.

Storage and AI. Blobs bills per operation and per gigabyte stored, so reading metadata instead of the object body, and deleting preview artefacts when a deploy is superseded, both count. Database compute is dominated by connection handling, which is why the HTTP driver is the default recommendation. Gateway tokens are billed per token, so truncating a prompt and capping maxTokens are the levers that matter, and an unauthenticated AI endpoint is a cost with someone else’s hand on it.

The unifying principle is that every meter needs an owner and a number. Governance provides the role that can see the usage dashboard; observability provides the log line that explains the spike; the plugin provides the hook that fails the deploy before the spike is deployed.


Complete Example Session

// ============================================
// PART 1: THE PLUGIN MANIFEST ENTRY
// ============================================
// Declared in netlify.toml (shown in the next block) with inputs.
// package = "./plugins/deploy-guard" and inputs.budgetSeconds.

// ============================================
// PART 2: PRE-BUILD VALIDATION
// ============================================
export const onPreBuild = async ({ constants, utils }) => {
  // Fail fast and cheap, before the build command spends minutes
  if (!constants.CONTEXT) {
    return utils.build.failPlugin("no deploy context โ€” running outside Netlify?");
  }
  utils.status.show({ title: "Guard", summary: `${constants.CONTEXT} / ${constants.BRANCH}` });
};

// ============================================
// PART 3: CACHE RESTORATION
// ============================================
export const onPreBuildCache = async ({ utils }) => {
  // A warm cache turns a four-minute install into seconds
  await utils.cache.restore("dependency-cache");
};

// ============================================
// PART 4: POST-BUILD BUDGET CHECK
// ============================================
export const onPostBuild = async ({ utils, inputs }) => {
  const { stdout } = await utils.run.command("du -sk dist | cut -f1");
  const kb = Number(stdout.trim());

  // Failing the build keeps the previous deploy live โ€” the right trade
  if (kb > inputs.maxKilobytes) {
    return utils.build.failBuild(`dist is ${kb} KB, budget ${inputs.maxKilobytes} KB`);
  }
  await utils.cache.save("dependency-cache");
};

// ============================================
// PART 5: THE ALWAYS-RUNS REPORTER
// ============================================
export const onEnd = async ({ constants, utils }) => {
  // onEnd fires for success and failure alike, so one report covers both
  await fetch(`${process.env.REPORT_ENDPOINT}/deploys`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      deploy: constants.DEPLOY_ID,
      context: constants.CONTEXT,
      commit: constants.COMMIT_REF,
    }),
  }).catch(() => utils.status.show({ title: "Report", summary: "ingest unreachable" }));
};

// ============================================
// PART 6: THE STRUCTURED FUNCTION LOG
// ============================================
// netlify/functions/search.js
export default async (req, context) => {
  const t0 = Date.now();
  const route = "search";
  const log = (level, msg, extra = {}) =>
    console.log(JSON.stringify({ level, msg, route, country: context.geo?.country?.code, ...extra }));

  const q = new URL(req.url).searchParams.get("q") ?? "";
  log("info", "query received", { len: q.length });

  // ============================================
  // PART 7: CACHING THE RESPONSE AT THE EDGE
  // ============================================
  const results = await search(q);
  log("info", "results", { count: results.length, ms: Date.now() - t0 });

  return new Response(JSON.stringify(results), {
    headers: {
      "Content-Type": "application/json",
      // Served from the CDN for 60s: repeat queries cost no invocation
      "Netlify-CDN-Cache-Control": "public, max-age=60, stale-while-revalidate=300",
    },
  });
};

// ============================================
// PART 8: READING A CONTEXT-SCOPED VARIABLE
// ============================================
export const readPayments = () => {
  // The value differs per deploy context; the code never branches on context
  const url = process.env.PAYMENTS_API_URL;
  if (!url) throw new Error("PAYMENTS_API_URL missing for this context");
  return url;
};

// ============================================
// PART 9: THE BUILD GUARD IN netlify.toml
// ============================================
// See the config block below.

// ============================================
// PART 10: THE HUMAN STEP
// ============================================
// Governance is not code: assign Reviewer to stakeholders who only read
// deploys, scope CI to a deploy key, and pin production deploys to `main`.
# ============================================
# THE PLUGIN DECLARATION
# ============================================
[[plugins]]
  package = "./plugins/deploy-guard"
  [plugins.inputs]
    maxKilobytes = 5000

[[plugins]]
  package = "@netlify/plugin-lighthouse"
  [plugins.inputs]
    # A performance floor enforced by the build, not by a review comment
    assertions = { "categories:performance" = ["error", { minScore = 0.9 }] }

The ten parts covered the manifest entry, a cheap pre-build validation, cache restoration, a post-build size budget, an always-runs reporter, a structured function log, edge response caching, a context-scoped variable read, the plugin declaration in configuration, and the human governance step that no plugin can enforce.


Quick Reference

Build Events

EventFiresTypical Use
onPreBuildBefore the build commandValidate, restore cache
onBuildAfter build, before deploySave cache, transform output
onPostBuildAfter the deploy is createdBudgets, reports on output
onSuccessOnly on successNotifications of a good deploy
onErrorOnly on failureDiagnostics, alerts
onEndAlways, lastCleanup, ingest that must run

Plugin Utilities

UtilityEffect
utils.status.show()Titled note in the deploy log
utils.build.failBuild()Cancels the deploy; previous version stays live
utils.build.failPlugin()Marks the plugin failed; deploy continues
utils.build.cancelBuild()Cancels without a failure marker
utils.run.command()Runs a shell command, returns stdout
utils.cache.save/restore/listManual cache control

Observability Layers

LayerResolutionWhere
Build logOne per deployDeploy list, netlify logs:deploy
Function logOne per invocationFunction tab, netlify logs:function
AnalyticsAggregate, server-sideAnalytics add-on
TracesPer request span treeObservability, OTLP export

Governance Controls

ControlScopePlan
Roles (Owner/Developer/Reviewer)TeamAll
SAML SSO, SCIM sync, audit logTeamEnterprise
Secret variablesEnvironmentAll
Per-context variable overridesDeploy contextAll
Branch deploy restrictionSiteEnterprise

Usage Levers

MeterPrimary Lever
Build minutesignore command, dependency cache
BandwidthImmutable cache headers, image CDN
Function invocationsNetlify-CDN-Cache-Control, remove polling
Function runtimeSmaller bundles, edge functions
BlobsMetadata reads, delete superseded artefacts
Gateway tokensPrompt truncation, maxTokens caps

Best Practices

โœ… Do This:

// Fail early in the lifecycle, not after the build
export const onPreBuild = async ({ utils }) => { /* validate */ };  // โœ…

// Use failBuild when the artefact is unacceptable
utils.build.failBuild("sitemap missing");                          // โœ…

// Use failPlugin when only the plugin is at fault
utils.build.failPlugin("lint warning");                            // โœ…

// Emit one JSON object per log line
console.log(JSON.stringify({ level: "info", route, ms }));         // โœ…

// Cache a response at the edge instead of re-invoking
"Netlify-CDN-Cache-Control": "public, max-age=60"                  // โœ…

// Scope variables per deploy context
[context.deploy-preview.environment]                               // โœ…

// Skip builds when nothing relevant changed
ignore = "git diff --quiet $CACHED_COMMIT_REF $COMMIT_REF ."       // โœ…

โŒ Don’t Do This:

// Do heavy validation in onPostBuild
export const onPostBuild = async () => { throw new Error("bad"); };  // โŒ

// Fail the deploy because a report endpoint was down
await fetch(url); // uncaught, no catch                                    // โŒ

// Log an unstructured string in a high-volume function
console.log("error");                                                     // โŒ

// Return a stack trace to the client
return new Response(err.stack, { status: 500 });                          // โŒ

// Share one API key across every deploy context
PAYMENTS_API_URL = "https://api.payments.example.com";                    // โŒ

// Let CI authenticate with a human's personal token
// (revoking the person breaks the pipeline)                              // โŒ

// Serve fingerprinted assets with max-age=60
Cache-Control = "public, max-age=60";                                     // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Deploy cancelled by a warningfailBuild used for a non-fatal checkSwitch to failPlugin
Cache never hitsSaved after the build that needed itRestore in onPreBuild, save in onBuild
Report lost on failed deploysLogic in onSuccess onlyMove unconditional work to onEnd
Function logs unusableFree-form stringsOne JSON object per line with level
Analytics disagrees with GA4Client-side blocked requestsTreat the gap as the blocked cohort
Preview charged a real cardOne key shared across contextsPer-context variable override
“Who deployed this?” unanswerableNo SSO or audit log on the planEnterprise audit, scoped deploy keys
Bandwidth spike after launchShort TTL on fingerprinted assetsmax-age=31536000, immutable

Real-World Examples

1. Skip unchanged builds

[build]
  ignore = "git diff --quiet $CACHED_COMMIT_REF $COMMIT_REF ."

2. Fail on a missing sitemap

onPostBuild: async ({ utils }) => {
  try { await utils.run.command("test -f dist/sitemap.xml"); }
  catch { utils.build.failBuild("sitemap missing"); }
}

3. Restore a dependency cache

export const onPreBuild = async ({ utils }) => utils.cache.restore("deps");

4. Fail only the plugin

utils.build.failPlugin("optional check failed");

5. Structured function log

console.log(JSON.stringify({ level: "warn", route: "checkout", ms: 412 }));

6. Tail a function’s log

netlify logs:function checkout

7. Immutable asset cache

[[headers]]
  for = "/assets/*"
  [headers.values]
    Cache-Control = "public, max-age=31536000, immutable"

8. Sandbox key for previews

[context.deploy-preview.environment]
  PAYMENTS_API_URL = "https://sandbox.payments.example.com"

9. Edge-cache a function response

headers: { "Netlify-CDN-Cache-Control": "public, max-age=60" }

10. Pin the toolchain

[build.environment]
  NODE_VERSION = "22"

Visual

The Build Lifecycle

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  BUILD LIFECYCLE                                        โ”‚
โ”‚                                                         โ”‚
โ”‚  deploy starts                                          โ”‚
โ”‚       โ”‚                                                 โ”‚
โ”‚       โ”œโ”€โ”€ onPreBuild     validate, restore cache        โ”‚
โ”‚       โ”œโ”€โ”€ build command  your framework build           โ”‚
โ”‚       โ”œโ”€โ”€ onBuild        save cache, transform output   โ”‚
โ”‚       โ”œโ”€โ”€ onPostBuild    budgets, inspect the output    โ”‚
โ”‚       โ”œโ”€โ”€ onSuccess      good deploy  (or onError)      โ”‚
โ”‚       โ””โ”€โ”€ onEnd          always last, cleanup, ingest   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Three Resolutions of Truth

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  THREE VIEWS OF ONE DEPLOY                              โ”‚
โ”‚                                                         โ”‚
โ”‚  build log      1 per deploy                            โ”‚
โ”‚                 duration, cache hit, plugin notes       โ”‚
โ”‚                                                         โ”‚
โ”‚  function log   1 per invocation                        โ”‚
โ”‚                 level, route, country, duration         โ”‚
โ”‚                                                         โ”‚
โ”‚  analytics      aggregate over CDN requests             โ”‚
โ”‚                 visitors, top pages, 404s               โ”‚
โ”‚                                                         โ”‚
โ”‚  tracing        span tree per request                   โ”‚
โ”‚                 correlates all of the above             โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Governance Layers

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  GOVERNANCE                                             โ”‚
โ”‚                                                         โ”‚
โ”‚  who      Owner  โ”€โ”€โ–บ billing, deletion                  โ”‚
โ”‚           Developer โ”€โ”€โ–บ deploys, settings, variables     โ”‚
โ”‚           Reviewer โ”€โ”€โ–บ read, comment, never deploy      โ”‚
โ”‚                                                         โ”‚
โ”‚  what     secret variables   (write-only)               โ”‚
โ”‚           per-context scope  (prod vs preview)          โ”‚
โ”‚           branch restriction (Enterprise)               โ”‚
โ”‚                                                         โ”‚
โ”‚  proof    audit log         (Enterprise)                โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Where the Meters Move

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  COST LEVERS                                            โ”‚
โ”‚                                                         โ”‚
โ”‚  builds      skip via ignore  + dependency cache        โ”‚
โ”‚  bandwidth   immutable headers + image CDN              โ”‚
โ”‚  functions   edge caching instead of re-invoking        โ”‚
โ”‚  storage     metadata reads instead of objects          โ”‚
โ”‚  tokens      truncate the prompt, cap maxTokens         โ”‚
โ”‚                                                         โ”‚
โ”‚  each lever maps to one meter on the bill               โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Plugin declaration[[plugins]] package = "..."
Lifecycle eventsonPreBuild, onBuild, onPostBuild, onSuccess, onError, onEnd
Hard stoputils.build.failBuild()
Soft stoputils.build.failPlugin()
Cache modescache: "manual" or cache: "netlify"
Build logOne per deploy, downloadable
Function logOne per invocation, streamed live
AnalyticsServer-side, no snippet, no undercount
Team rolesOwner, Developer, Reviewer
Enterprise addsSAML SSO, SCIM, custom roles, audit log
Biggest build savingignore command + dependency cache

Key takeaways:

  • A plugin is the only supported hook into the deploy. The six events are ordered and each has a failure semantic, so a check belongs in onPreBuild if it is cheap and in onPostBuild only if it needs the output.
  • failBuild and failPlugin are not interchangeable. The first cancels the deploy and keeps the previous version live; the second records a warning and lets a good artefact ship.
  • onEnd is the reporting hook. It runs after success and after failure, which makes it the only correct place for ingest that must record both outcomes.
  • Caching must be restored before it is saved. A plugin that saves in onBuild and restores in onPostBuild has never hit its cache, and the log will show a cold start on every deploy.
  • Structured logs turn a log into a dataset. One JSON object per line with level, route, and duration is filterable; a prose string is greppable and nothing more.
  • Analytics is server-side, so it counts what client scripts miss. The totals will never match a client-side tool, and the difference is the blocked cohort rather than an error in either.
  • Governance is scoping before it is permission. Per-context variables stop a preview from charging a real card; secret variables stop a key from being copied into chat; the audit log proves who deployed.
  • Every meter has one dominant lever. Skipping unchanged builds, immutable asset caching, and edge-caching function responses address the three largest line items on most accounts.

Remember: The deploy is an event with an author, a duration, a cost, and a postmortem, and these three features are three ways of treating it as one. A build plugin acts on the event while it is happening, and its most valuable habit is failing cheaply and early. Observability reads the event afterwards, at three different resolutions that must not be confused with each other. Governance bounds the event beforehand โ€” who may trigger it, what credentials it can see, and what it is permitted to spend. Build the plugin that enforces the budget, log in a shape you can query, scope the keys per context, and the invoice stops being a surprise and starts being a number you chose.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!