Netlify 19 ๐ Identity, AI Gateway & Extensions โ Integrating authentication, unified AI model routing, and Netlify SDK extensions
Three separate problems push a site toward Netlify’s platform services. The first is knowing who is making a request. A static site can serve a login page, but something has to issue a token, store it, expire it, and hand the server a way to trust it. That something is Netlify Identity โ a hosted authentication service with a client widget, a JWT, and role claims that functions and redirects can both read.
The second problem is model access. An AI feature needs an API key, a billing account, a rate limit, and a provider SDK, and every one of those is a credential that must not end up in a bundle. Netlify AI Gateway removes the keys from the equation entirely: the deploy environment is given provider credentials automatically, the SDKs pick them up from ordinary environment variables, and the usage lands in the Netlify dashboard instead of three separate provider consoles.
The third problem is where all of this becomes visible. A team running identity, functions, databases, and AI traffic has four dashboards and one Netlify site. Netlify SDK extensions exist so that the missing view can be built as a panel inside the site dashboard, backed by API handlers and build event handlers that run inside the deploy lifecycle.
This chapter covers the three in that order: the identity widget and its token, the gateway and its credential-free routing, and the extension SDK’s surfaces. It closes with a session that wires an extension panel to identity and gateway data, because the three features are more useful together than apart.
Key point: Identity issues a JWT that functions verify server-side and redirects can gate by role, AI Gateway injects provider credentials at deploy time so model calls need no key in your code, and an SDK extension is the place to surface both โ a panel in the site dashboard backed by API handlers and build event handlers.
Why exists
The credential problem. Any secret shipped to the browser is not a secret. An AI key in a client bundle is published the moment it deploys, and a key in a .env file is a rotation chore across every environment. Both Identity and the AI Gateway exist to move credentials out of the application and into the platform, where they can be issued, scoped, rotated, and revoked without a redeploy.
The trust problem. A frontend that “knows” a user is logged in is a UI state, not a security boundary. A request arriving at a function carries a token, and the function must decide whether that token is valid, unexpired, and issued for this site. Identity exists because writing that verification by hand โ signing keys, refresh windows, revocation lists โ is a multi-week project that nobody budgets for.
The multi-provider problem. A feature that tries three models against each other to compare quality needs three accounts, three SDKs, and three key rotations. The AI Gateway exists so that provider selection is a string in code rather than a credential-management exercise, and so that every call is metered in one place.
The rate-limit problem. An unauthenticated AI endpoint is a free inference proxy for anyone who finds it. The gateway applies platform-level limits, so a runaway loop costs a rate limit rather than a month of provider invoices. The application still needs its own rules, but the last line of defence is not the application’s.
The observability problem. Usage spread across providers, environments, and team members is invisible in aggregate. The gateway records tokens and requests per site, which is the number that matters when deciding whether a feature is affordable.
The adjacency problem. Everything above produces data that lives in Netlify’s systems โ users, roles, token counts, build outputs. Without an extension, reading that data means opening the Netlify UI, exporting a CSV, and pasting it somewhere. Extensions exist to put the derived view next to the site it describes.
a. Netlify Identity โ the widget, the JWT, and role claims
Identity is enabled per site in the dashboard, and the first decision is registration policy: open registration, invite-only, or closed to external providers only. The second decision is which external providers to accept โ Google, GitHub, GitLab, Bitbucket โ each of which requires an OAuth application configured with the site’s callback URL.
The client side is a widget bundle that manages a token in local storage and exposes a small event-driven API. The widget is deliberately plain: it renders a modal, it holds the session, and it emits events when the state changes.
<!-- index.html โ the widget and its initialisation -->
<script src="https://identity.netlify.com/v1/netlify-identity-widget.js"></script>
<script>
// init() reads the widget's config and restores any existing session
netlifyIdentity.init();
// The "login" event fires for password login, signup confirmation,
// and OAuth callback alike โ one handler covers every path
netlifyIdentity.on("login", (user) => {
// user.jwt() is the signed token to send to functions
console.log("signed in as", user.email, user.app_metadata.roles);
renderDashboard();
});
netlifyIdentity.on("logout", () => renderLoginPrompt());
document.querySelector("#signin").addEventListener("click", () => {
netlifyIdentity.open("login"); // "signup" opens the registration tab
});
</script>
The token is the interesting object. user.jwt() returns a signed JSON Web Token with an exp claim, a sub claim carrying the user id, and an app_metadata block that includes a roles array. The same token is written to an nf_jwt cookie when the widget is in use, which is what allows role-based redirects to work without any JavaScript at the edge.
Roles are assigned in the dashboard per user, or programmatically through the Identity admin API. They are namespaced under app_metadata specifically so a user cannot grant themselves one โ everything under user_metadata is self-editable and therefore untrusted.
# _redirects โ role-gated routes resolved at the edge, no function involved
/admin/* /admin/index.html 200! Role=admin,editor
/account/* /account/index.html 200! Role=member
The Role condition is matched against the JWT in the nf_jwt cookie. An unauthenticated request or a token without the role falls through to the next rule rather than being served the file, so the usual companion is a catch-all redirect to a login page.
Server-side verification is the part that must not be skipped. In a classic handler the platform has already decoded the token and placed the claims on context.clientContext.user, but the modern Request/Response functions receive a raw Authorization header and the handler has to verify it.
// netlify/functions/admin-report.ts
export default async (req: Request) => {
const header = req.headers.get("authorization") ?? "";
const token = header.startsWith("Bearer ") ? header.slice(7) : null;
if (!token) return new Response("unauthorized", { status: 401 });
// Ask the identity service who this token belongs to โ this is the
// authoritative check, not a local decode, because it also fails
// tokens for deleted or banned users.
const res = await fetch(`${process.env.URL}/.netlify/identity/user`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) return new Response("invalid token", { status: 401 });
const user = await res.json();
// Roles are read from app_metadata, which users cannot write to
const roles: string[] = user.app_metadata?.roles ?? [];
if (!roles.includes("admin")) return new Response("forbidden", { status: 403 });
return Response.json({ email: user.email, roles });
};
Three rules follow. Never trust a role read from user_metadata. Never treat the presence of a token as authorisation โ verification is a round trip or a signature check, not a localStorage read. And never let the client decide what it is allowed to fetch, because the client is the attacker’s environment.
An important caveat: Identity is a long-standing service and Netlify has positioned it as a mature, maintenance-mode product rather than an actively growing one. It remains fully functional, and the widget and API are stable, but sites starting fresh in 2025 should weigh it against bringing an external identity provider. For an internal tool or a gated marketing site, the zero-setup path is still the shortest.
b. Netlify AI Gateway โ credential-free model routing
The gateway does one thing that changes the shape of an AI feature: it supplies provider credentials to the deploy environment so that application code never contains a key. When the gateway is active, the environment has OPENAI_API_KEY, ANTHROPIC_API_KEY, and the Google equivalent populated automatically, pointing at a gateway endpoint that proxies to the real provider and records usage on the way through.
This means the standard provider SDKs work unmodified, because they all read the same environment variables.
// netlify/functions/summarise.ts
import { generateText } from "ai";
import { createAnthropic } from "@ai-sdk/anthropic";
// createAnthropic() with no argument reads ANTHROPIC_API_KEY,
// which the gateway has already populated. No key in the repo.
const anthropic = createAnthropic();
export default async (req: Request) => {
const { text } = await req.json();
const { text: summary, usage } = await generateText({
model: anthropic("claude-3-5-sonnet-latest"),
prompt: `Summarise in one sentence:\n\n${text}`,
maxTokens: 200,
});
// usage carries promptTokens and completionTokens for this call
return Response.json({ summary, tokens: usage.totalTokens });
};
Switching providers is a change of import and model string, not a change of credentials. That is what makes an A/B comparison between models a ten-minute experiment rather than a procurement process.
// The same request routed to three providers for a quality comparison
import { createOpenAI } from "@ai-sdk/openai";
import { createAnthropic } from "@ai-sdk/anthropic";
import { createGoogleGenerativeAI } from "@ai-sdk/google";
// Each factory resolves its own key from the environment
const candidates = [
{ name: "openai", model: createOpenAI()("gpt-4o-mini") },
{ name: "anthropic", model: createAnthropic()("claude-3-5-sonnet-latest") },
{ name: "google", model: createGoogleGenerativeAI()("gemini-2.0-flash") },
];
const results = await Promise.all(
candidates.map(async ({ name, model }) => {
const { text } = await generateText({ model, prompt, maxTokens: 120 });
return { name, text };
})
);
Streaming is the pattern that makes an AI feature feel fast, and it is the pattern that a serverless function gets wrong by default. A function that awaits the full completion holds the invocation open for the entire generation; a function that returns a ReadableStream releases as tokens arrive.
import { streamText } from "ai";
import { createOpenAI } from "@ai-sdk/openai";
export default async (req: Request) => {
const { prompt } = await req.json();
const result = streamText({
model: createOpenAI()("gpt-4o-mini"),
prompt,
});
// toTextStreamResponse() returns a Response with a streaming body,
// so the client receives tokens progressively
return result.toTextStreamResponse();
};
Two operational details matter. The first is that local development is not automatically credentialed: netlify dev proxies the gateway when the site is linked, but a plain node run has no such proxy, so the local .env needs a real key. The second is that the gateway is a shared budget. Every call is metered per site, and an endpoint reachable without authentication is a way for someone else to spend it โ which loops directly back to Identity. Gate the AI endpoint with a verified token, and add a per-user rate limit in Blobs or the database if the feature is expensive.
// A cheap guard: one request per user per minute, stored in Blobs
import { getStore } from "@netlify/blobs";
async function allow(userId: string) {
const store = getStore({ name: "ai-throttle", consistency: "strong",
siteID: process.env.NETLIFY_SITE_ID, token: process.env.NETLIFY_BLOBS_TOKEN });
const key = `${userId}:${Math.floor(Date.now() / 60_000)}`;
if (await store.get(key)) return false; // already used this minute
await store.set(key, "1", { metadata: { ttl: "60" } });
return true;
}
c. Netlify SDK extensions โ surfaces, API handlers, and build events
An extension is a packaged integration that runs inside Netlify’s product. The manifest describes it, the Extension class declares what it adds, and the pieces are three: a UI surface rendered in the Netlify app, API handlers that the UI calls, and build event handlers that run during a deploy.
# integration.toml โ the generated manifest
name = "Site Insights"
description = "Identity counts and AI Gateway usage in one panel"
slug = "site-insights"
# Scopes requested at install time; keep this list minimal
scopes = ["read:site", "read:environment"]
[[surfaces]]
surface = "site-dashboard"
path = "/"
title = "Insights"
The TypeScript entry point constructs the extension and attaches each piece. The surface name determines where the UI appears โ site-dashboard is a panel on an individual site, team-dashboard is a panel on the team, and the *-configuration surfaces are settings pages.
// src/index.ts
import { Extension } from "@netlify/sdk";
const extension = new Extension({
name: "Site Insights",
description: "Identity counts and AI Gateway usage in one panel",
slug: "site-insights",
});
// A panel inside a single site's dashboard
extension.addSurface({
surface: "site-dashboard",
path: "/",
title: "Insights",
});
// The UI calls this handler; it runs server-side with the install context
extension.addApiHandler({
path: "/api/summary",
method: "GET",
handler: async (event, context) => {
// The SDK client in context is already authorised for this install
return {
statusCode: 200,
body: JSON.stringify({ generatedAt: new Date().toISOString() }),
};
},
});
export { extension };
The build event handler is the piece that runs without any user interaction. It fires at named points in the deploy lifecycle โ before the build, after the build, on success, on error, on end โ and it receives the build context, which includes the deploy id and the site id.
// A post-build handler that records what shipped
extension.addBuildEventHandler("onPostBuild", async ({ utils, constants }) => {
// utils exposes the build's logging and status helpers
utils.status.show({ title: "Insights", summary: "Recording build metadata" });
// constants carries deploy and site identifiers for this run
const record = {
deployId: constants.DEPLOY_ID,
siteId: constants.SITE_ID,
at: new Date().toISOString(),
};
// A failure here should warn, not fail the deploy โ the artefact is fine
try {
await fetch(`${process.env.INSIGHTS_INGEST_URL}/builds`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(record),
});
} catch (err) {
utils.build.failPlugin("ingest unreachable", { error: err });
}
});
The UI side is a React application. It runs inside the Netlify app’s shell, so it must use the SDK’s fetch client rather than window.fetch โ the client attaches the install’s credentials and routes to your API handler.
// src/ui/main.tsx
import { NetlifyExtensionUIFetchClient } from "@netlify/sdk/ui/react";
const fetchClient = new NetlifyExtensionUIFetchClient();
export function InsightsPanel() {
const [data, setData] = useState<{ generatedAt: string } | null>(null);
useEffect(() => {
// The client knows the extension's install and API base URL
fetchClient.fetch("/api/summary").then(async (r) => setData(await r.json()));
}, []);
if (!data) return <p>Loadingโฆ</p>;
return <p>Snapshot generated at {new Date(data.generatedAt).toLocaleString()}</p>;
}
Development is a local loop: the extension runs against a linked site so the surfaces render in a dev shell, and the API handlers run in the same process. Publishing registers the extension so it can be installed on a site, at which point the panel appears for every user who has access to that site.
The design constraint worth respecting is scope. An extension asks for permissions at install time, and a broad scope list is the fastest way to have an install request declined. Ask for read:site when reading is all the panel does, and never ask for write access to satisfy a feature that has not been built yet.
Complete Example Session
// ============================================
// PART 1: THE IDENTITY GATE
// ============================================
// netlify/functions/_auth.ts
export async function requireUser(req: Request) {
const token = req.headers.get("authorization")?.replace("Bearer ", "");
if (!token) return null;
// Authoritative check against the identity service
const res = await fetch(`${process.env.URL}/.netlify/identity/user`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) return null;
return (await res.json()) as { id: string; email: string; app_metadata: { roles?: string[] } };
}
// ============================================
// PART 2: A PROTECTED AI ENDPOINT
// ============================================
// netlify/functions/ask.ts
import { streamText } from "ai";
import { createAnthropic } from "@ai-sdk/anthropic";
import { requireUser } from "./_auth.js";
const anthropic = createAnthropic(); // key injected by the gateway
export default async (req: Request) => {
const user = await requireUser(req);
if (!user) return new Response("unauthorized", { status: 401 });
const { prompt } = await req.json();
// ============================================
// PART 3: THE MODEL CALL
// ============================================
const result = streamText({
model: anthropic("claude-3-5-sonnet-latest"),
prompt,
maxTokens: 500,
});
// Streaming response: the function releases as tokens arrive
return result.toTextStreamResponse();
};
// ============================================
// PART 4: THE CLIENT CALL
// ============================================
async function ask(prompt: string) {
const user = netlifyIdentity.currentUser();
if (!user) throw new Error("not signed in");
// user.jwt() is the token the function verifies
const res = await fetch("/.netlify/functions/ask", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${user.jwt()}`,
},
body: JSON.stringify({ prompt }),
});
return res.body; // a stream, consumed with a reader
}
// ============================================
// PART 5: ROLE-GATED ROUTES
// ============================================
// _redirects
// /admin/* /admin/index.html 200! Role=admin
// /account/* /account/index.html 200! Role=member
// The nf_jwt cookie created by the widget is what the edge reads.
// ============================================
// PART 6: THE EXTENSION MANIFEST
// ============================================
// integration.toml
// name = "Site Insights"
// slug = "site-insights"
// scopes = ["read:site"]
// [[surfaces]]
// surface = "site-dashboard"
// path = "/"
// title = "Insights"
// ============================================
// PART 7: THE EXTENSION ENTRY POINT
// ============================================
import { Extension } from "@netlify/sdk";
const extension = new Extension({
name: "Site Insights",
description: "Identity counts and AI Gateway usage in one panel",
slug: "site-insights",
});
extension.addSurface({ surface: "site-dashboard", path: "/", title: "Insights" });
// ============================================
// PART 8: THE API HANDLER
// ============================================
extension.addApiHandler({
path: "/api/summary",
method: "GET",
handler: async () => {
// In a real extension this would call Netlify's APIs with the
// install token available on the context, then aggregate.
return {
statusCode: 200,
body: JSON.stringify({ users: 42, monthlyTokens: 184_000 }),
};
},
});
// ============================================
// PART 9: THE BUILD EVENT HANDLER
// ============================================
extension.addBuildEventHandler("onPostBuild", async ({ utils, constants }) => {
utils.status.show({ title: "Insights", summary: `Deploy ${constants.DEPLOY_ID}` });
// Ingestion failures warn rather than fail an otherwise-good deploy
});
export { extension };
// ============================================
// PART 10: THE PANEL
// ============================================
// src/ui/main.tsx
// const client = new NetlifyExtensionUIFetchClient();
// client.fetch("/api/summary") -> { users, monthlyTokens }
// Rendered as a card grid inside the site dashboard.
The ten parts covered the identity gate, a protected AI endpoint, the model call, the authenticated client request, role-gated redirects, the extension manifest, the entry point, an API handler, a post-build handler, and the UI panel that reads it.
Quick Reference
Identity Surface
| Item | Value |
|---|---|
| Client bundle | netlify-identity-widget.js |
| Session token | user.jwt() |
| Cookie | nf_jwt |
| Role location | app_metadata.roles |
| Verify endpoint | /.netlify/identity/user |
| Redirect syntax | Role=admin,editor |
| Provider options | Google, GitHub, GitLab, Bitbucket |
AI Gateway
| Item | Value |
|---|---|
| Injected keys | Provider API keys, at deploy time |
| Providers | OpenAI, Anthropic, Google Gemini |
| SDK requirement | Any SDK reading standard env vars |
| Streaming | toTextStreamResponse() |
| Metering | Per site, in the Netlify dashboard |
| Local dev | Linked site via netlify dev, else own key |
Extension Building Blocks
| Piece | Declaration | Runs |
|---|---|---|
| UI surface | addSurface() | In the Netlify app |
| API handler | addApiHandler() | Server-side, per install |
| Build event | addBuildEventHandler() | During a deploy |
| Manifest | integration.toml | At install time |
| Scopes | scopes = [...] | Granted at install |
Best Practices
โ Do This:
// Verify the token server-side before trusting it
const res = await fetch(`${URL}/.netlify/identity/user`, { headers }); // โ
// Read roles from app_metadata only
const roles = user.app_metadata?.roles ?? []; // โ
// Send the JWT on every function call
Authorization: `Bearer ${user.jwt()}` // โ
// Let the gateway supply the key
const anthropic = createAnthropic(); // โ
// Stream long generations
return result.toTextStreamResponse(); // โ
// Request the narrowest scope that works
scopes = ["read:site"] // โ
// Warn, don't fail, on non-critical post-build errors
utils.build.failPlugin("ingest unreachable", { error: err }); // โ
โ Don’t Do This:
// Ship a provider key to the browser
const key = "sk-..."; // โ
// Treat a token's presence as authorisation
if (token) return adminData(); // โ
// Trust self-editable metadata for roles
const roles = user.user_metadata.roles; // โ
// Leave an AI endpoint unauthenticated
// (it is an open inference proxy) // โ
// Await a full generation in a short function
const { text } = await generateText({ /* long */ }); // โ
// Ask for write scopes you have not implemented
scopes = ["read:site", "write:site"] // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Key exposed in the bundle | Client-side SDK initialised with a literal | Route through the gateway or a function |
| 401 on every call | Authorization header omitted | Attach user.jwt() |
| Admin route serves publicly | Rule lacks a Role condition | Add Role=admin to _redirects |
| Role check passes for anyone | Roles read from user_metadata | Read app_metadata.roles |
| AI endpoint abused | No auth and no rate limit | Verify the token and throttle per user |
| Gateway key missing locally | Running outside netlify dev | Supply a real key in .env for local |
| Panel blank in the Netlify app | window.fetch used | Use the SDK’s fetch client |
| Install request declined | Scopes broader than the feature | Request read: scopes only |
Real-World Examples
1. Initialise the widget
netlifyIdentity.init();
netlifyIdentity.on("login", (u) => start(u.jwt()));
2. Open the signup modal
netlifyIdentity.open("signup");
3. Gate a route by role
/admin/* /admin/index.html 200! Role=admin
4. Verify a token
const res = await fetch(`${URL}/.netlify/identity/user`, { headers });
5. Read roles safely
const roles = user.app_metadata?.roles ?? [];
6. Gateway-provided client
const openai = createOpenAI(); // key from the environment
7. Stream a completion
return streamText({ model, prompt }).toTextStreamResponse();
8. Compare three models
for (const m of candidates) await generateText({ model: m, prompt });
9. Declare a dashboard surface
extension.addSurface({ surface: "site-dashboard", path: "/", title: "Insights" });
10. Post-build ingest
extension.addBuildEventHandler("onPostBuild", async ({ constants }) => { /* ... */ });
Visual
The Identity Token Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ IDENTITY FLOW โ
โ โ
โ browser โโโบ netlifyIdentity.open("login") โ
โ โ โ
โ โผ โ
โ /.netlify/identity/token โ
โ โ โ
โ โผ โ
โ JWT in localStorage + nf_jwt cookie โ
โ โ โ
โ โโโโโโโโโโโโโโดโโโโโโโโโโโโโโ โ
โ โผ โผ โ
โ edge reads nf_jwt fetch with Authorization โ
โ Role=admin match function verifies token โ
โ โ โ โ
โ โผ โผ โ
โ gated static file claims from app_metadata โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Gateway Routing
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ AI GATEWAY โ
โ โ
โ function โโโบ createAnthropic() โ
โ โ โ
โ โผ โ
โ ANTHROPIC_API_KEY from the env โ
โ โ โ
โ โผ โ
โ gateway proxy endpoint โ
โ โ โ
โ โโโโโโโโโโโโโผโโโโโโโโโโโโ โ
โ โผ โผ โผ โ
โ OpenAI Anthropic Google โ
โ โโโโโโโโโโโโโผโโโโโโโโโโโโ โ
โ โผ โ
โ usage metered per site โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Extension Anatomy
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ EXTENSION PARTS โ
โ โ
โ integration.toml โโโบ name, scopes, surfaces โ
โ โ
โ addSurface() โโโบ panel in the Netlify app โ
โ โ โ
โ โผ โ
โ addApiHandler() โโโบ server-side data for the panel โ
โ โ
โ addBuildEventHandler() โโโบ runs during each deploy โ
โ โ โ
โ โผ โ
โ onPreBuild onPostBuild onSuccess onError onEnd โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Layered Trust
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ TRUST LAYERS โ
โ โ
โ client UI knows the user is signed in (cosmetic)โ
โ โ โ
โ โผ โ
โ edge redirect trusts nf_jwt for static gating โ
โ โ โ
โ โผ โ
โ function verifies the token against identity โ
โ โ โ
โ โผ โ
โ gateway holds the credential, meters the call โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Identity client | netlify-identity-widget.js |
| Token | user.jwt(), also nf_jwt cookie |
| Role claim | app_metadata.roles |
| Edge gating | Role= condition in _redirects |
| Server check | /.netlify/identity/user with bearer token |
| Gateway purpose | Inject provider keys, meter usage |
| Providers | OpenAI, Anthropic, Google Gemini |
| Streaming | toTextStreamResponse() |
| Extension entry | new Extension({ name, slug }) |
| Surface kinds | site-dashboard, team-dashboard, config pages |
| Build events | onPreBuild, onPostBuild, onSuccess, onError, onEnd |
Key takeaways:
- Identity’s token is the boundary. The widget gives the browser a JWT; the function must verify it against the identity service and read roles from
app_metadata, becauseuser_metadatais user-editable and therefore attacker-controlled. - Role gating can happen without code. The
nf_jwtcookie plus aRole=condition in_redirectsprotects static files at the edge, which is faster and simpler than a guarding function. - The AI Gateway removes keys from the repository. Provider credentials are injected at deploy time, so any SDK reading standard environment variables works unchanged and provider comparison is a model string rather than a procurement step.
- Streaming is the difference between a fast feature and a timeout. A function that awaits the full completion holds the invocation open; returning a text stream releases as tokens arrive.
- The gateway is a shared budget. It meters per site, so an unauthenticated AI endpoint costs money for anyone who finds it. Verify the token and add a per-user throttle.
- Extensions are three pieces, not one. A surface renders in the Netlify app, API handlers supply its data, and build event handlers run inside the deploy lifecycle without user interaction.
- Scopes are requested at install time. A broad permission list makes an extension harder to install, so ask only for what the shipped feature actually reads.
Remember: These three services answer three questions about the same request โ who is calling, what may they spend, and where is that recorded. Identity answers the first with a verified token and a role claim. The AI Gateway answers the second by holding the credential and metering the call. An extension answers the third by putting the derived view on the site dashboard it belongs to. Wire them in that order: authenticate the endpoint, let the gateway supply the model credential, then build the panel that shows the traffic the first two produced.
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!