Netlify
Web Hosting Platform
Netlify
Overview
Netlify is a cloud platform for Jamstack sites offering a comprehensive solution with continuous deployment, form handling, identity management, Edge Functions, and CMS integrations. As a pioneer of the Jamstack ecosystem, it maintains a solid position with rich developer features and a comprehensive ecosystem, continuously supported for static site development.
Details
Founded in 2014, Netlify is the pioneering company that popularized the JAMstack (JavaScript, APIs, Markup) architecture. It provides integrated solutions including Git-connected automatic deployments, form handling, identity management, Edge Functions, and A/B testing features, supporting the entire static site development workflow. Particularly known for intuitive UI/UX for frontend developers and a rich plugin ecosystem. With continuous feature enhancements like Netlify CMS and Netlify Functions focused on developer productivity, it supports projects from small-scale to large enterprise sites.
Advantages and Disadvantages
Advantages
- Comprehensive JAMstack Solution: Centralized management from deployment to form processing and authentication
- Excellent Git Integration: Branch-based preview and rollback functionality
- Rich Plugin Ecosystem: Feature extensions through hundreds of plugins
- Form Handling: Serverless form processing and spam protection features
- Identity Management: Easy implementation of OAuth and JWT authentication
- A/B Testing Features: Built-in split testing functionality
- Excellent Documentation: Rich learning resources and community support
Disadvantages
- Build Time Limitations: Free plan limited to 300 minutes per month
- Bandwidth Restrictions: Additional charges for increased traffic
- Complex Pricing Structure: Tiered billing based on features and usage
- High Learning Curve: Initial learning burden due to extensive features
Reference Pages
Code Examples
Basic Setup and Project Configuration
# Install Netlify CLI
npm install -g netlify-cli
# Login and site initialization
netlify login
netlify init
# Start development server
netlify dev
# Test Functions locally
netlify functions:serve
# netlify.toml - Basic configuration
[build]
publish = "dist"
command = "npm run build"
functions = "netlify/functions"
[build.environment]
NODE_VERSION = "18"
NPM_VERSION = "9"
[[redirects]]
from = "/api/*"
to = "/.netlify/functions/:splat"
status = 200
[[headers]]
for = "/*"
[headers.values]
X-Frame-Options = "DENY"
X-XSS-Protection = "1; mode=block"
Static Site Deployment
# Manual deployment
netlify deploy --prod --dir=dist
# Deploy from specific branch
netlify deploy --alias=staging
# Drag & drop deployment
netlify deploy --dir=./build --prod
# Automatic deployment with GitHub Actions
name: Deploy to Netlify
on:
push:
branches: [ main ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build
run: npm run build
- name: Deploy to Netlify
uses: nwtgck/[email protected]
with:
publish-dir: './dist'
production-branch: main
github-token: ${{ secrets.GITHUB_TOKEN }}
deploy-message: "Deploy from GitHub Actions"
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
Framework Integration (Next.js, React, Vue)
// netlify/functions/api.js - Next.js API Routes style
exports.handler = async (event, context) => {
const { httpMethod, path, body } = event;
// CORS headers
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE'
};
if (httpMethod === 'OPTIONS') {
return { statusCode: 200, headers, body: '' };
}
try {
let response;
switch (httpMethod) {
case 'GET':
response = await handleGet(path);
break;
case 'POST':
response = await handlePost(JSON.parse(body));
break;
default:
return {
statusCode: 405,
headers,
body: JSON.stringify({ error: 'Method not allowed' })
};
}
return {
statusCode: 200,
headers: { ...headers, 'Content-Type': 'application/json' },
body: JSON.stringify(response)
};
} catch (error) {
return {
statusCode: 500,
headers,
body: JSON.stringify({ error: error.message })
};
}
};
# Nuxt.js configuration
[build]
command = "npm run generate"
publish = "dist"
[build.environment]
NODE_VERSION = "18"
[[redirects]]
from = "/_nuxt/*"
to = "/_nuxt/:splat"
status = 200
# SPA mode configuration
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
Custom Domains and SSL
# Add custom domain
netlify domains:create example.com
netlify domains:add example.com
# SSL certificate setup (automatic)
# Netlify automatically configures Let's Encrypt
# Check DNS configuration
netlify dns
# netlify.toml - Domain related configuration
[[redirects]]
from = "https://www.example.com/*"
to = "https://example.com/:splat"
status = 301
force = true
[[headers]]
for = "/*"
[headers.values]
Strict-Transport-Security = "max-age=31536000; includeSubDomains; preload"
Content-Security-Policy = "default-src 'self'; script-src 'self' 'unsafe-inline'"
Serverless Functions and APIs
// netlify/functions/hello.js - Basic Function
exports.handler = async (event, context) => {
const { name = 'World' } = event.queryStringParameters || {};
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'public, max-age=60'
},
body: JSON.stringify({
message: `Hello ${name}!`,
timestamp: new Date().toISOString(),
source: 'Netlify Functions'
})
};
};
// netlify/functions/users.ts - TypeScript Function
import { Handler } from '@netlify/functions';
import { createClient } from '@supabase/supabase-js';
const supabase = createClient(
process.env.SUPABASE_URL!,
process.env.SUPABASE_ANON_KEY!
);
export const handler: Handler = async (event, context) => {
const { httpMethod, body, path } = event;
try {
switch (httpMethod) {
case 'GET':
const { data: users, error } = await supabase
.from('users')
.select('*');
if (error) throw error;
return {
statusCode: 200,
body: JSON.stringify(users)
};
case 'POST':
const userData = JSON.parse(body || '{}');
const { data: newUser, error: insertError } = await supabase
.from('users')
.insert([userData])
.select();
if (insertError) throw insertError;
return {
statusCode: 201,
body: JSON.stringify(newUser)
};
default:
return {
statusCode: 405,
body: JSON.stringify({ error: 'Method not allowed' })
};
}
} catch (error) {
return {
statusCode: 500,
body: JSON.stringify({ error: error.message })
};
}
};
CI/CD and Production Optimization
# netlify.toml - Optimization configuration
[build]
command = "npm run build"
publish = "dist"
functions = "netlify/functions"
[build.processing]
skip_processing = false
[build.processing.css]
bundle = true
minify = true
[build.processing.js]
bundle = true
minify = true
[build.processing.html]
pretty_urls = true
[build.processing.images]
compress = true
# Preview deploy configuration
[context.deploy-preview]
command = "npm run build:preview"
[context.branch-deploy]
command = "npm run build:staging"
# Environment variables
[context.production.environment]
NODE_ENV = "production"
GATSBY_ACTIVE_ENV = "production"
// netlify/functions/build-hook.js - Build trigger
const crypto = require('crypto');
exports.handler = async (event, context) => {
// Webhook authentication
const signature = event.headers['x-netlify-signature'];
const payload = event.body;
const secret = process.env.WEBHOOK_SECRET;
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(payload, 'utf8')
.digest('hex');
if (signature !== expectedSignature) {
return {
statusCode: 401,
body: JSON.stringify({ error: 'Unauthorized' })
};
}
// Automatic build on CMS update
const buildHookUrl = process.env.BUILD_HOOK_URL;
try {
const response = await fetch(buildHookUrl, {
method: 'POST',
body: JSON.stringify({ trigger: 'CMS update' })
});
return {
statusCode: 200,
body: JSON.stringify({
message: 'Build triggered successfully',
buildId: response.headers.get('x-netlify-build-id')
})
};
} catch (error) {
return {
statusCode: 500,
body: JSON.stringify({ error: error.message })
};
}
};
# Netlify CLI command collection
netlify status # Check site status
netlify build # Local build
netlify deploy --build # Build + deploy
netlify functions:list # List Functions
netlify addons:list # Check addons
netlify env:list # Check environment variables
netlify logs:functions # Check Function logs