### Programmatic Database Setup and Teardown (TypeScript) Source: https://docs.netlify.com/build/data-and-storage/netlify-database/local-development Example of starting, using, and stopping the Netlify database emulator within a test suite. It demonstrates applying migrations and connecting a client to the database. ```ts let db: NetlifyDB; let connectionString: string; beforeAll(async () => { db = new NetlifyDB(); connectionString = await db.start(); await db.applyMigrations("./netlify/database/migrations"); }); afterAll(async () => { await db.stop(); }); test("inserts and reads a user", async () => { const client = new Client({ connectionString }); await client.connect(); await client.query("INSERT INTO users (name) VALUES ($1)", ["Ada"]); const { rows } = await client.query("SELECT name FROM users"); expect(rows).toEqual([{ name: "Ada" }]); await client.end(); }); ``` -------------------------------- ### Programmatic Full Netlify Environment Setup and Teardown (TypeScript) Source: https://docs.netlify.com/build/data-and-storage/netlify-database/local-development Example of starting and stopping the full Netlify development environment programmatically. This sets up the `NETLIFY_DB_URL` environment variable for functions to use. ```ts const netlifyDev = new NetlifyDev({ projectRoot: "./fixtures/my-project", }); await netlifyDev.start(); // `NETLIFY_DB_URL` is now set in the runtime; functions, edge functions, // and any other code under test can read it as they would in production. // ...run your tests... await netlifyDev.stop(); ``` -------------------------------- ### Initialize Netlify Database with CLI Source: https://docs.netlify.com/build/data-and-storage/netlify-database/getting-started Use the `netlify database init` command for an interactive setup that installs necessary packages, configures query style, and scaffolds migrations. ```bash netlify database init ``` -------------------------------- ### Install Netlify TanStack Start Vite Plugin Source: https://docs.netlify.com/build/frameworks/framework-setup-guides/tanstack-start Install the Netlify TanStack Start Vite plugin as a development dependency. ```bash npm install -D @netlify/vite-plugin-tanstack-start ``` -------------------------------- ### Copy Environment Variables Source: https://docs.netlify.com/build/frameworks/framework-setup-guides/hydrogen Copy the example environment variables to a new file for local development setup. ```bash cp .env.example .env ``` -------------------------------- ### Install Async Workloads Library Source: https://docs.netlify.com/build/async-workloads/sending-events Install the @netlify/async-workloads library using npm, pnpm, or yarn. ```bash npm install @netlify/async-workloads ``` ```bash pnpm add @netlify/async-workloads ``` ```bash yarn add @netlify/async-workloads ``` -------------------------------- ### Create a New Project with Netlify CLI Source: https://docs.netlify.com/deploy/create-deploys Use `netlify create` to generate, deploy, and download a project based on a natural language description. This command initiates a guided process for project setup. ```bash netlify create ``` -------------------------------- ### Install @netlify/cache Source: https://docs.netlify.com/build/caching/cache-api Install the @netlify/cache module using npm. ```bash npm install @netlify/cache ``` -------------------------------- ### Install Gatsby Adapter for Netlify Source: https://docs.netlify.com/build/frameworks/framework-setup-guides/gatsby?gatsby-version=essential Install the `gatsby-adapter-netlify` package using npm. This is the first step for manual installation and configuration. ```bash npm install gatsby-adapter-netlify ``` -------------------------------- ### Install @netlify/aws-lambda-compat Source: https://docs.netlify.com/build/functions/api Install the compatibility package using npm. ```bash npm install @netlify/aws-lambda-compat ``` -------------------------------- ### Install Netlify Adapter with npm Source: https://docs.netlify.com/build/frameworks/framework-setup-guides/sveltekit Install the SvelteKit Netlify adapter as a development dependency using npm. ```bash npm install -D @sveltejs/adapter-netlify ``` -------------------------------- ### Install Netlify Adapter with Yarn Source: https://docs.netlify.com/build/frameworks/framework-setup-guides/sveltekit Install the SvelteKit Netlify adapter as a development dependency using Yarn. ```bash yarn add -D @sveltejs/adapter-netlify ``` -------------------------------- ### Initialize Netlify Database Source: https://docs.netlify.com/build/data-and-storage/netlify-database/cli Sets up Netlify Database in your project. Use `--yes` to accept defaults and skip interactive prompts, which is useful for CI environments. ```bash netlify database init ``` ```bash netlify database init --yes ``` -------------------------------- ### Example Site Creation Output Source: https://docs.netlify.com/manage/visual-editor/get-started/set-up-visual-editor-locally Illustrates the expected output and prompts during the `netlify sites:create-template` command execution. ```bash netlify sites:create-template content-ops-starter ✔ ? Team: Netlify Testing ? Site name (leave blank for a random name; you can change it later): docs-test- site-for-visual-editor-setup Site Created Admin URL: https://app.netlify.com/sites/YOUR_SITE_NAME URL: [REDACTED] Site ID: [REDACTED] Repo URL: https://github.com/REPO-OWNER/YOUR_SITE_NAME ? Do you want to clone the repository? Yes 🚀 Repository cloned successfully. You can find it under the YOUR_SITE_NAME folder ``` -------------------------------- ### Complete 'Hello, World!' Go Function Example Source: https://docs.netlify.com/build/functions/lambda-compatibility A complete Go function example that returns a 'Hello, World!' message with a 200 status code. This function deploys to an endpoint at /.netlify/functions/hello. ```go package main import ( "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" ) func handler(request events.APIGatewayProxyRequest) (*events.APIGatewayProxyResponse, error) { return &events.APIGatewayProxyResponse{ StatusCode: 200, Body: "Hello, World!", }, nil } func main() { lambda.Start(handler) } ``` -------------------------------- ### Get Help for a Specific Command Source: https://docs.netlify.com/api-and-cli-guides/cli-guides/get-started-with-cli Append 'help' to a command to get specific usage information for that command. For example, 'netlify help deploy'. ```bash netlify help deploy ``` -------------------------------- ### Navigate and Start React Development Server Source: https://docs.netlify.com/build/frameworks/framework-setup-guides/react Change to your project directory and start the development server to view your React app locally. ```bash cd my-app npm start ``` -------------------------------- ### Get General CLI Help Source: https://docs.netlify.com/api-and-cli-guides/cli-guides/get-started-with-cli Run 'netlify help' to display usage tips and a list of available commands in the Netlify CLI. ```bash netlify help ``` -------------------------------- ### Configure Sanity Content Source in Stackbit Source: https://docs.netlify.com/manage/visual-editor/content-sources/sanity Example configuration for Sanity as a content source using Next.js. Ensure `@stackbit/cms-sanity` is installed. ```typescript // stackbit.config.ts import { defineStackbitConfig } from "@stackbit/types"; import { SanityContentSource } from "@stackbit/cms-sanity"; export default defineStackbitConfig({ stackbitVersion: "~0.6.0", ssgName: "nextjs", nodeVersion: "16", contentSources: [ new SanityContentSource({ rootPath: __dirname, studioPath: path.join(__dirname, "studio"), studioUrl: "https://project.sanity.studio", projectId: process.env.SANITY_PROJECT_ID!, token: process.env.SANITY_ACCESS_TOKEN!, dataset: process.env.SANITY_DATASET || "production" }) ], mapModels: ({ models }) => { return models.map(model => { if (model.name === "page") { return { ...model, type: "page", urlPath: "/{slug}" }; } return model; }); } }); ``` -------------------------------- ### Install Local Plugin in netlify.toml Source: https://docs.netlify.com/extend/develop-and-share/develop-build-plugins Specify the absolute path to your local plugin folder in the `package` field of `netlify.toml`. The path must start with `.` or `/`. ```toml # netlify.toml [[plugins]] package = "/plugins/netlify-plugin-hello-world" ``` -------------------------------- ### Example Deploy Prompt for AI Tool Source: https://docs.netlify.com/start/quickstarts/deploy-from-ai-code-generation-tool Use this prompt when asking your AI tool to deploy a project to Netlify. It requests clear explanations suitable for beginners while retaining technical terms for debugging. ```markdown Deploy this project to Netlify. Ask me questions if you need more details. To help reduce complexity, explain as if I'm new to web development but still use the technical terms I'd need to understand for debugging, troubleshooting, and looking up more information. ``` -------------------------------- ### Scaffold Vite Project with pnpm Source: https://docs.netlify.com/build/frameworks/framework-setup-guides/vite Use this command to start a new Vite project with pnpm. Ensure Node.js version 18.14.0 or later is installed. ```bash pnpm create vite ``` -------------------------------- ### Initialize Netlify CLI for Manual Setup Source: https://docs.netlify.com/api-and-cli-guides/cli-guides/get-started-with-cli Use `netlify init --manual` for manual repository connection on GitLab, Bitbucket, Azure DevOps, or GitHub. This prompts for deploy settings and provides a deploy key and webhook URL for manual addition to your Git provider. ```bash netlify init --manual ``` -------------------------------- ### Scaffold Vite Project with yarn Source: https://docs.netlify.com/build/frameworks/framework-setup-guides/vite Use this command to start a new Vite project with yarn. Ensure Node.js version 18.14.0 or later is installed. ```bash yarn create vite ``` -------------------------------- ### Scaffold Vite Project with npm Source: https://docs.netlify.com/build/frameworks/framework-setup-guides/vite Use this command to start a new Vite project with npm. Ensure Node.js version 18.14.0 or later is installed. ```bash npm create vite@latest ``` -------------------------------- ### Configure npm and local plugins in netlify.toml Source: https://docs.netlify.com/extend/install-and-use/build-plugins Use this configuration to install a plugin published to npm and a local plugin. Ensure local plugins start with '.' or '/'. ```toml # Configuration for a plugin published to npm [[plugins]] package = "netlify-plugin-lighthouse" [plugins.inputs] output_path = "reports/lighthouse.html" # Configuration for a local plugin [[plugins]] package = "/plugins/netlify-plugin-hello-world" ``` -------------------------------- ### Create Site and Deploy From ZIP File Source: https://docs.netlify.com/api-and-cli-guides/api-guides/get-started-with-api This command creates a new site and immediately deploys it from a ZIP file in a single HTTP request. It's a convenient way to set up a new site with initial content. ```bash curl -H "Content-Type: application/zip" \ -H "Authorization: Bearer YOUR_OAUTH2_ACCESS_TOKEN" \ --data-binary "@website.zip" \ https://api.netlify.com/api/v1/sites ``` -------------------------------- ### Specify Required Extensions in netlify.toml Source: https://docs.netlify.com/deploy/create-deploys List required Netlify extensions for a template to function correctly. Users will be prompted to install these extensions, facilitating a faster setup. ```toml [template] required-extensions = ["supabase"] ``` -------------------------------- ### Build and Deploy Website with Netlify Source: https://docs.netlify.com/build/build-with-ai/agent-setup-guides/use-netlify-with-chatgpt Use this command to have ChatGPT build a website and deploy it to Netlify. Requires Netlify connection. ```markdown Can you build me a website for my restaurant and deploy it to @Netlify? ``` -------------------------------- ### Complete Synchronous Go Function Example Source: https://docs.netlify.com/build/functions/lambda-compatibility?fn-language=ts A complete Go function example that returns a 'Hello, World!' message with a 200 status code. This function deploys to an endpoint relative to the site's base URL. ```go package main import ( "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" ) func handler(request events.APIGatewayProxyResponse) (*events.APIGatewayProxyResponse, error) { return &events.APIGatewayProxyResponse{ StatusCode: 200, Body: "Hello, World!", }, nil } func main() { lambda.Start(handler) } ``` -------------------------------- ### Get Blob Example Source: https://docs.netlify.com/ai-context/netlify-development.mdc Retrieves a stored blob. Avoid adding the second argument unless a specific type is required. If the blob is missing, the promise resolves with null. ```typescript // example: await store.get('key-name'); // - NEVER add the second arg unless you need an explicit type 'arrayBuffer' | 'blob' | 'json' | 'stream' | 'text'. // - Instead of using JSON.parse(blob), use store.get('key-name', {type: 'json'}) ``` -------------------------------- ### Initialize Stripe Project Source: https://docs.netlify.com/extend/install-and-use/setup-guides/stripe-projects Create and initialize your app or site with Stripe Projects from your local project's directory. Replace YOUR_PROJECT_NAME with your desired project name. ```bash stripe projects init YOUR_PROJECT_NAME ``` -------------------------------- ### Example SQL Migration File Source: https://docs.netlify.com/ai-context/netlify-development.mdc A sample SQL file for a migration, demonstrating the creation of a `users` table with common data types and constraints. ```sql -- netlify/database/migrations/20260301143000_create_users/migration.sql CREATE TABLE users ( id SERIAL PRIMARY KEY, name TEXT NOT NULL, email TEXT UNIQUE NOT NULL, created_at TIMESTAMP DEFAULT NOW() ); ``` -------------------------------- ### Example _headers file with specific paths Source: https://docs.netlify.com/manage/routing/headers Define custom headers for specific URL paths in a _headers file. Lines starting with '#' are comments. Header names are case-insensitive. ```netlify-headers # a path: /templates/index.html # headers for that path: X-Frame-Options: DENY # another path: /templates/index2.html # headers for that path: X-Frame-Options: SAMEORIGIN ``` -------------------------------- ### Get Metadata Only Example Source: https://docs.netlify.com/ai-context/netlify-development.mdc Retrieves only the metadata of a blob without downloading the data. The second argument is for explicit types or etag checks. If the blob is missing, the promise resolves with null. ```typescript // example: await store.getMetadata('key-name'); // - NEVER add the second getOpts arg unless you need an explicit type or have an etag to check against. // - AVOID adding it unless it's reliably available but IF an etag is provided, it will only return the blob if the etag is different that what's stored. ``` -------------------------------- ### Install and configure a build plugin Source: https://docs.netlify.com/build/configure-builds/file-based-configuration Add build plugins to your site by specifying the package name and any necessary inputs in the `[[plugins]]` section. This allows for extending build process functionality. ```toml [[plugins]] package = "netlify-plugin-check-output-for-puppy-references" [plugins.inputs] breeds = ["pomeranian", "chihuahua", "bulldog"] ``` -------------------------------- ### Get Blob with Metadata Example Source: https://docs.netlify.com/ai-context/netlify-development.mdc Retrieves a blob along with its metadata. The second argument should only be used for explicit types or etag checks. If the blob is missing, the promise resolves with null. ```typescript // example: await store.getWithMetadata('key-name'); // - NEVER add the second getOpts arg unless you need an explicit type or have an etag to check against. // - AVOID adding it unless it's reliably available but IF an etag is provided, it will only return the blob if the etag is different that what's stored. ``` -------------------------------- ### Example stackbit.config.ts for ContentOps Starter Source: https://docs.netlify.com/manage/visual-editor/get-started/troubleshoot-visual-editor-setup This is an example of a `stackbit.config.ts` file used with the ContentOps Starter template, which utilizes Git CMS. It demonstrates how to configure the visual editor to understand site content structure and locate content files. ```typescript import { defineConfig } from '@stackbit/sdk'; export default defineConfig({ stackbitVersion: '~0.6.0', contentSources: [ { type: 'git', repoUrl: 'https://github.com/netlify-templates/content-ops-starter', contentPath: 'content', models: { page: { type: 'data', urlPath: '/pages' }, post: { type: 'data', urlPath: '/posts' } } } ], theme: { // ... } }); ``` -------------------------------- ### Hello World Builder Example (JavaScript) Source: https://docs.netlify.com/build/configure-builds/on-demand-builders A basic 'Hello World' example in JavaScript demonstrating a builder function that returns an HTML page. This response is cached at the edge. ```javascript const { builder } = require("@netlify/functions") async function handler(event, context) { return { statusCode: 200, headers: { "Content-Type": "text/html", }, body: "
Hello World ", }; } exports.handler = builder(handler); ``` -------------------------------- ### Generate Edge Function for API Routes Source: https://docs.netlify.com/build/frameworks/frameworks-api Create an edge function to intercept requests for JSON and rewrite them to an API path. This example intercepts all paths except those already starting with /api/. ```typescript import type { Config, Context } from "@netlify/edge-functions"; export default async (req: Request, context: Context) => { if (req.headers.get("accept") === "application/json") { const { pathname } = new URL(req.url) return new URL(`/api${pathname}`, req.url) } } export const config: Config = { // Configures the paths on which the edge function runs. // The value below lets you intercept requests for any path. path: "/*", // Sometimes it's useful to exclude certain paths. // This example will ignore requests that are // already targeting an `/api/` path. excludedPath: ["/api/*"] }; ``` -------------------------------- ### Example Build Command Source: https://docs.netlify.com/build/frameworks/overview This is an example of a typical build command used to build a site with a static site generator or build tool. The command runs in the Bash shell. ```bash npm run build ``` -------------------------------- ### Get blob data in a Build Plugin Source: https://docs.netlify.com/build/data-and-storage/netlify-blobs This example shows how to retrieve blob data using a Build Plugin during the post-build phase. It logs the entry if found, or a message indicating it was not found. ```javascript export const onPostBuild = async () => { const uploads = getDeployStore("file-uploads"); const entry = await uploads.get("my-key"); if (entry === null) { console.log("Could not find entry"); } else { console.log(entry); } }; ``` -------------------------------- ### Get blob data in an Edge Function Source: https://docs.netlify.com/build/data-and-storage/netlify-blobs This example demonstrates how to retrieve blob data within an Edge Function. It extracts the key from URL parameters and handles cases where the entry might not be found. ```typescript export default async (req: Request, context: Context) => { // Extract key from URL. const { key } = context.params; const uploads = getStore("file-uploads"); const entry = await uploads.get(key); if (entry === null) { return new Response(`Could not find entry with key ${key}`, { status: 404 }); } return new Response(entry); }; ``` -------------------------------- ### Recommended Project Structure for Go Functions Source: https://docs.netlify.com/build/functions/lambda-compatibility?fn-language=go This example shows the recommended directory structure for managing Go functions and their dependencies within a Netlify project. Ensure your Go function files are placed within the `netlify/functions/` directory. ```go my-base-directory/ ├─ go.mod ├─ go.sum ├─ netlify/ └─ functions/ ├─ hello-world └─ process-data ``` -------------------------------- ### Create a Netlify Project from a Prompt Source: https://docs.netlify.com/api-and-cli-guides/cli-guides/get-started-with-cli Generate, deploy, and download a new Netlify project using a natural language description. This command leverages Agent Runners for automated build and deployment. ```bash netlify create "a landing page for a SaaS product with a waitlist signup" ``` -------------------------------- ### Deploy to Netlify Button URL Example Source: https://docs.netlify.com/deploy/create-deploys This is an example of the URL structure for the Deploy to Netlify button, specifying the repository to clone. ```txt https://app.netlify.com/start/deploy?repository=https://github.com/netlify/netlify-statuskit ``` -------------------------------- ### Initialize LaunchDarkly Client and Get Feature Flag Source: https://docs.netlify.com/extend/install-and-use/setup-guides/launchdarkly-integration Initialize the LaunchDarkly client with your client-side ID and retrieve the value of a feature flag. This example demonstrates basic usage within a Netlify function context. ```typescript export default { async fetch(request: Request, env: Bindings): Promise