| | |

Netlify 21 ๐ŸŒ Cheatsheet

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

Dense reference for everything from the last five chapters โ€” deploys, functions, forms, blobs, database, identity, AI gateway, extensions, build plugins, and governance. Copy, paste, ship.


CLI

npm i -g netlify-cli                  # install globally
netlify login                         # authenticate
netlify link                          # associate cwd with a site
netlify init                          # create + link a new site
netlify dev                           # local server with functions + redirects
netlify build                         # run the build locally, same plugins
netlify deploy                        # draft deploy to a preview URL
netlify deploy --prod                 # production deploy
netlify open                          # open the site dashboard
netlify env:list                      # list env vars (secrets redacted)
netlify env:set KEY value             # set a variable
netlify logs:function <name>          # tail a function's log
netlify logs:deploy --deploy <id>     # fetch a deploy's build log
netlify db init                       # provision managed Postgres
netlify db connect                    # SQL session against a branch
netlify extensions:dev                # run an extension locally

netlify.toml

[build]
  command   = "npm run build"
  publish   = "dist"
  functions = "netlify/functions"
  # skip the build when nothing that affects output changed
  ignore    = "git diff --quiet $CACHED_COMMIT_REF $COMMIT_REF ."

[build.environment]
  NODE_VERSION = "22"                 # pin the toolchain

[dev]
  framework = "#custom"
  command   = "npm run dev"
  port      = 8888

[context.production.environment]
  API_URL = "https://api.example.com"

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

[[redirects]]
  from   = "/old/*"
  to     = "/new/:splat"
  status = 301

[[redirects]]
  from   = "/api/*"
  to     = "/.netlify/functions/:splat"
  status = 200

[[redirects]]
  from    = "/admin/*"
  to      = "/admin/index.html"
  status  = 200
  force   = true
  conditions = { Role = ["admin"] }

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

[[headers]]
  for = "/*"
  [headers.values]
    Strict-Transport-Security = "max-age=31536000; includeSubDomains"
    Referrer-Policy           = "strict-origin-when-cross-origin"

[[plugins]]
  package = "@netlify/plugin-lighthouse"

Edge Functions

// netlify/edge-functions/auth.ts โ€” runs at the CDN PoP, no cold start
import type { Config, Context } from "@netlify/edge-functions";

export default async (req: Request, context: Context) => {
  const token = context.cookies.get("session");
  if (!token) return Response.redirect(new URL("/login", req.url), 302);

  // Rewrite to the origin without a redirect round trip
  return context.next();
};

export const config: Config = {
  path: ["/app/*"],          // exact, glob, or an array of both
  excludedPath: "/app/public/*",
  cache: "manual",           // "off" | "manual"
};

Serverless Functions

// netlify/functions/hello.ts โ€” modern Request/Response signature
export default async (req: Request, context: Context) => {
  const body = await req.json();
  return Response.json({ ok: true, body }, { status: 201 });
};

// Classic Handler signature (Node)
import type { Handler } from "@netlify/functions";
export const handler: Handler = async (event, context) => ({
  statusCode: 200,
  body: JSON.stringify({ path: event.path }),
});
# netlify.toml โ€” control the bundle for one function
[functions]
  node_bundler = "esbuild"
  external_node_modules = ["sharp"]

[functions.hello]
  included_files = ["data/*.json"]

Async Workloads (Workflows)

import { workflow } from "@netlify/workflows";

export const order = workflow("order-process", async ({ step }) => {
  // Each step is checkpointed; retries resume from the last success
  const o = await step.run("validate", async () => ({ id: "1", ok: true }));

  await step.run(
    "charge",
    {
      retries: 5,
      backoff: { initialInterval: "10s", multiplier: 2, maxInterval: "1h" },
    },
    async () => chargeCard(o.id)
  );

  // Pause for a duration โ€” no compute, no billing
  await step.sleep("trial-end", "3d");

  // Pause for an external signal โ€” resumes on webhook
  const shipped = await step.waitForEvent("shipment-delivered", { timeout: "7d" });
});
CallEffect
step.run(name, fn)Checkpointed, retried on failure
step.sleep(name, "3d")Suspends compute free of charge
step.waitForEvent(name, { timeout })Resume on external signal

Forms

<form name="contact" method="POST" data-netlify="true" netlify-honeypot="bot-field">
  <input type="hidden" name="form-name" value="contact" />
  <p hidden><input name="bot-field" /></p>
  <input name="email" required />
  <button>Send</button>
</form>
<!-- SPA: hidden static stub so the deploy-time parser registers the form -->
<form name="contact" data-netlify="true" hidden>
  <input type="hidden" name="form-name" value="contact" />
</form>
// Programmatic submit โ€” form-name is mandatory
await fetch("/", {
  method: "POST",
  body: new URLSearchParams({ "form-name": "contact", email }),
});

// With a file โ€” multipart + FormData
await fetch("/", { method: "POST", body: new FormData(form) });
// netlify/functions/submission-created.ts โ€” event fires per submission
export const handler: Handler = async (event) => {
  const { payload } = JSON.parse(event.body ?? "{}");
  if (payload.form_name !== "contact") return { statusCode: 200 };
  // payload: { id, form_name, data, human_fields, ordered_human_fields, created_at }
  return { statusCode: 200 };
};
AttributePlaced onPurpose
data-netlify="true"formRegisters the form at deploy time
form-namehidden inputRoutes the POST to that form
netlify-honeypotformNames the bot-bait field
enctype="multipart/form-data"formRequired for uploads

Blobs

import { getStore } from "@netlify/blobs";

const store = getStore("uploads");

await store.set("notes/a.txt", "text");
await store.setJSON("cfg/site.json", { theme: "dark" });
await store.set("img/logo.png", buf, {
  metadata: { contentType: "image/png", originalName: "logo.png" },
});

await store.get("notes/a.txt");                                    // text
await store.get("cfg/site.json", { type: "json" });                // parsed
await store.get("img/logo.png", { type: "arrayBuffer" });          // bytes
await store.get("big.bin", { type: "stream" });                    // no buffer
await store.getWithMetadata("img/logo.png");                        // { data, metadata }
await store.getMetadata("img/logo.png");                            // metadata only

for await (const e of store.list({ prefix: "notes/" })) { /* ... */ }
await store.list({ directories: true, prefix: "uploads/" });
await store.delete("notes/a.txt");                                  // idempotent

// Strong consistency โ€” read-after-write, needs explicit credentials
const strict = getStore({
  name: "sessions",
  consistency: "strong",
  siteID: process.env.NETLIFY_SITE_ID,
  token:  process.env.NETLIFY_BLOBS_TOKEN,
});
typeReturns
text (default)string
jsonparsed object
arrayBufferraw bytes
blobBlob
streamReadableStream

Database

npx netlify db init                # provision Neon Postgres, inject URL
// HTTP driver โ€” one query per request, no socket, no pool exhaustion
import { neon } from "@netlify/neon";
const sql = neon();

const rows = await sql`SELECT * FROM notes WHERE published = ${true} LIMIT ${20}`;

// TCP driver โ€” required for sessions and transactions
import { Pool } from "@neondatabase/serverless";
let pool;
const getPool = () => (pool ??= new Pool({
  connectionString: process.env.NETLIFY_DATABASE_URL,
  max: 3,
}));

const c = await getPool().connect();
try {
  await c.query("BEGIN");
  /* ... */
  await c.query("COMMIT");
} catch (e) {
  await c.query("ROLLBACK");
  throw e;
} finally {
  c.release();
}
-- netlify/database/migrations/20250114103000_add_notes.sql
CREATE TABLE IF NOT EXISTS notes (
  id bigserial PRIMARY KEY,
  title text NOT NULL,
  published boolean NOT NULL DEFAULT false
);

-- Safe column addition: nullable โ†’ backfill โ†’ constrain
ALTER TABLE notes ADD COLUMN IF NOT EXISTS slug text;
UPDATE notes SET slug = lower(title) WHERE slug IS NULL;
ALTER TABLE notes ALTER COLUMN slug SET NOT NULL;
ConcernBehaviour
Connection varNETLIFY_DATABASE_URL per deploy context
IsolationOne copy-on-write branch per Deploy Preview
Fork sourceProduction branch at deploy time
RollbackForward-only; compensating migration
DDLNever in a handler, always a migration

Identity

<script src="https://identity.netlify.com/v1/netlify-identity-widget.js"></script>
<script>
  netlifyIdentity.init();
  netlifyIdentity.on("login",  (u) => send(u.jwt()));
  netlifyIdentity.on("logout", () => render());
  netlifyIdentity.open("signup");   // or "login"
</script>
// Server-side verification โ€” the authoritative check
const res = await fetch(`${process.env.URL}/.netlify/identity/user`, {
  headers: { Authorization: `Bearer ${token}` },
});
const user = await res.json();
const roles = user.app_metadata?.roles ?? [];   // never user_metadata
# _redirects โ€” edge gate, no function
/admin/*   /admin/index.html   200!   Role=admin
/account/* /account/index.html 200!   Role=member
ItemLocation
Session tokenuser.jwt(), nf_jwt cookie
Roles (trusted)app_metadata.roles
Roles (untrusted)user_metadata

AI Gateway

import { generateText, streamText } from "ai";
import { createOpenAI }      from "@ai-sdk/openai";
import { createAnthropic }   from "@ai-sdk/anthropic";
import { createGoogleGenerativeAI } from "@ai-sdk/google";

// Keys injected by the gateway โ€” no literal in the repo
const openai    = createOpenAI();
const anthropic = createAnthropic();
const google    = createGoogleGenerativeAI();

// Non-streaming
const { text, usage } = await generateText({
  model: anthropic("claude-3-5-sonnet-latest"),
  prompt,
  maxTokens: 200,
});

// Streaming โ€” function releases as tokens arrive
return streamText({ model: openai("gpt-4o-mini"), prompt }).toTextStreamResponse();
ProviderEnv var injected
OpenAIOPENAI_API_KEY
AnthropicANTHROPIC_API_KEY
GoogleGOOGLE_GENERATIVE_AI_API_KEY

Extensions

# integration.toml
name   = "Site Insights"
slug   = "site-insights"
scopes = ["read:site"]

[[surfaces]]
surface = "site-dashboard"
path    = "/"
title   = "Insights"
import { Extension } from "@netlify/sdk";

const extension = new Extension({ name: "Site Insights", slug: "site-insights" });

extension.addSurface({ surface: "site-dashboard", path: "/", title: "Insights" });

extension.addApiHandler({
  path: "/api/summary",
  method: "GET",
  handler: async (event, context) => ({
    statusCode: 200,
    body: JSON.stringify({ users: 42 }),
  }),
});

extension.addBuildEventHandler("onPostBuild", async ({ utils, constants }) => {
  utils.status.show({ title: "Insights", summary: constants.DEPLOY_ID });
});

export { extension };
// src/ui/main.tsx โ€” use the SDK fetch client, not window.fetch
import { NetlifyExtensionUIFetchClient } from "@netlify/sdk/ui/react";
const client = new NetlifyExtensionUIFetchClient();
client.fetch("/api/summary").then((r) => r.json());
SurfaceWhere rendered
site-dashboardPanel on an individual site
team-dashboardPanel on the team
*-configurationSettings page

Build Plugins

// plugins/guard/index.js
export const onPreBuild  = async ({ constants, utils }) => { /* validate */ };
export const onBuild     = async ({ utils })           => utils.cache.save("deps");
export const onPostBuild = async ({ utils, inputs })   => {
  if (kb() > inputs.maxKilobytes) return utils.build.failBuild("budget");
};
export const onSuccess   = async ({ utils })           => { /* good deploy */ };
export const onError     = async ({ utils })           => { /* failed deploy */ };
export const onEnd       = async ({ constants })       => {
  // Always runs โ€” the only correct place for unconditional reporting
};
EventFiresTypical use
onPreBuildBefore build commandValidate, restore cache
onBuildAfter build, before deploySave cache, transform
onPostBuildAfter deploy createdBudgets, inspect output
onSuccessOnly on successGood-deploy notification
onErrorOnly on failureDiagnostics
onEndAlways, lastCleanup, ingest
UtilityEffect
utils.status.show()Note in deploy log
utils.build.failBuild()Cancel deploy, previous stays live
utils.build.failPlugin()Fail only the plugin
utils.run.command()Shell command, returns stdout
utils.cache.save/restore/listManual cache
constants.CONTEXTproduction, deploy-preview, branch-deploy, dev

Observability

// One JSON object per line โ€” filterable, not greppable
const log = (level, msg, extra = {}) =>
  console.log(JSON.stringify({
    level,
    msg,
    route:   "checkout",
    country: context.geo?.country?.code,
    ms:      Date.now() - t0,
    ...extra,
  }));
// Cache a function response at the edge โ€” repeats cost no invocation
return new Response(body, {
  headers: {
    "Netlify-CDN-Cache-Control": "public, max-age=60, stale-while-revalidate=300",
  },
});
LayerResolutionWhere
Build log1 per deploynetlify logs:deploy
Function log1 per invocationnetlify logs:function
AnalyticsAggregate, server-sideAnalytics add-on
TracesSpan tree per requestObservability, OTLP export

Governance

RoleCan deploy?Can change settings?Billing?
OwnerYesYesYes
DeveloperYesYesNo
ReviewerNoNoNo
# netlify.toml โ€” governance as config
[context.production.environment]
  PAYMENTS_API_URL = "https://api.payments.example.com"

[context.deploy-preview.environment]
  PAYMENTS_API_URL = "https://sandbox.payments.example.com"
ControlScopePlan
Secret variablesWrite-only in UIAll
Per-context overrideDeploy contextAll
SAML SSO + SCIMTeam loginEnterprise
Audit logWho did what whenEnterprise
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 tokensTruncate prompts, cap maxTokens

Redirects & Headers

Redirect patternResult
/old /new 301Single 301
/old/* /new/:splat 301Wildcard with splat
/api/* /.netlify/functions/:splat 200Functions proxy
/admin/* /admin/index.html 200! Role=adminGated SPA route
/* /index.html 200SPA fallback
[[redirects]]
  from   = "/api/*"
  to     = "/.netlify/functions/:splat"
  status = 200
  force  = true
HeaderBest value for
Cache-Control: public, max-age=31536000, immutableFingerprinted assets
Cache-Control: public, max-age=0, must-revalidateHTML pages
Strict-Transport-Security: max-age=31536000; includeSubDomainsEvery site
Referrer-Policy: strict-origin-when-cross-originEvery site

Environment Variables

VariableSet byPurpose
URLNetlifySite’s primary URL
DEPLOY_URLNetlifyThis deploy’s unique URL
DEPLOY_IDNetlifyDeploy identifier
CONTEXTNetlifyproduction, deploy-preview, etc.
BRANCHNetlifyGit branch name
COMMIT_REFNetlifyCurrent commit SHA
CACHED_COMMIT_REFNetlifyPrevious built commit
NETLIFY_DATABASE_URLdb initPostgres connection string
NETLIFY_BLOBS_TOKENManualRequired for strong consistency
NETLIFY_SITE_IDManualRequired for strong consistency

Gotchas

SymptomCauseFix
Form missing from dashboardClient-JS-only renderHidden static stub in built HTML
Submission returns 404No form-name fieldAdd the hidden input
Uploads arrive emptyMissing multipart/form-dataSet enctype, send FormData
Stale read after writeDefault eventual consistencyconsistency: "strong" + creds
Preview broke on new columnMigration only ran on prodMigrations run per branch
Connection pool exhaustedTCP in a fan-out of invocationsneon() or reduce max
AI endpoint abusedNo auth on the handlerVerify token + per-user throttle
Preview charged a real cardOne key across contextsPer-context override
Function logs unusableFree-form stringsOne JSON object per line
Bandwidth spikeShort TTL on hashed assetsmax-age=31536000, immutable

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!