Learn NETLIFY-FUNCTIONS with Real Code Examples
Updated Nov 25, 2025
Code Sample Descriptions
1
Simple Netlify Function (JavaScript)
# netlify/demo/hello.js
exports.handler = async function(event, context) {
return {
statusCode: 200,
body: 'Hello, Netlify!'
};
}
A simple Netlify Function responding with 'Hello, Netlify!' to HTTP requests.
2
Netlify Function with Query Parameters
# netlify/demo/query.js
exports.handler = async function(event, context) {
const name = event.queryStringParameters.name || 'Guest';
return {
statusCode: 200,
body: `Hello, ${name}!`
};
}
Reads query parameters and responds with a personalized message.
3
Netlify Function with JSON Response
# netlify/demo/json.js
exports.handler = async function(event, context) {
return {
statusCode: 200,
body: JSON.stringify({ message: 'Hello, JSON!' })
};
}
Returns a JSON object in the response body.
4
Netlify Function with POST Body
# netlify/demo/post.js
exports.handler = async function(event, context) {
const data = JSON.parse(event.body || '{}');
return {
statusCode: 200,
body: `Received: ${data.input}`
};
}
Handles POST requests and parses JSON body.
5
Netlify Function with Environment Variables
# netlify/demo/env.js
exports.handler = async function(event, context) {
const secret = process.env.MY_SECRET || 'No Secret';
return {
statusCode: 200,
body: `Secret is: ${secret}`
};
}
Uses environment variables in the function.
6
Netlify Function Redirect Example
# netlify/demo/redirect.js
exports.handler = async function(event, context) {
return {
statusCode: 302,
headers: { 'Location': 'https://www.netlify.com/' },
body: ''
};
}
Responds with a redirect to another URL.
7
Netlify Function Error Handling
# netlify/demo/error.js
exports.handler = async function(event, context) {
try {
throw new Error('Something went wrong');
} catch(err) {
return {
statusCode: 500,
body: err.message
};
}
}
Demonstrates returning an error response.
8
Netlify Function Delayed Response
# netlify/demo/delay.js
exports.handler = async function(event, context) {
await new Promise(resolve => setTimeout(resolve, 1000));
return {
statusCode: 200,
body: 'Delayed Hello!'
};
}
Returns a response after a simulated delay.
9
Netlify Function Fetch External API
# netlify/demo/fetch.js
const fetch = require('node-fetch');
exports.handler = async function(event, context) {
const res = await fetch('https://api.github.com');
const data = await res.json();
return {
statusCode: 200,
body: JSON.stringify(data)
};
}
Fetches data from an external API and returns it.
10
Netlify Function with Custom Headers
# netlify/demo/headers.js
exports.handler = async function(event, context) {
return {
statusCode: 200,
headers: { 'X-Custom-Header': 'NetlifyFunction' },
body: 'Hello with headers'
};
}
Returns custom HTTP headers in the response.