Learn VERCEL-SERVERLESS with Real Code Examples
Updated Nov 25, 2025
Code Sample Descriptions
1
Simple Vercel Serverless Function (JavaScript)
# vercel/demo/hello.js
export default function handler(req, res) {
res.status(200).send('Hello, Vercel!');
}
A simple Vercel Serverless Function that responds with 'Hello, Vercel!' to HTTP requests.
2
Vercel Serverless Function with JSON Response
# vercel/demo/json.js
export default function handler(req, res) {
res.status(200).json({ message: 'Hello JSON!' });
}
A function returning JSON data.
3
Vercel Function with Query Parameters
# vercel/demo/query.js
export default function handler(req, res) {
const name = req.query.name || 'Guest';
res.status(200).send('Hello, ' + name);
}
A function that reads query parameters and responds accordingly.
4
Vercel Function Handling POST Request
# vercel/demo/post.js
export default function handler(req, res) {
if (req.method === 'POST') {
const data = req.body;
res.status(200).json({ received: data });
} else {
res.status(405).send('Method Not Allowed');
}
}
A function that handles POST requests with JSON payload.
5
Vercel Function with Environment Variables
# vercel/demo/env.js
export default function handler(req, res) {
const apiKey = process.env.MY_API_KEY;
res.status(200).send('API Key length: ' + apiKey.length);
}
A function using environment variables from Vercel.
6
Vercel Function Redirect
# vercel/demo/redirect.js
export default function handler(req, res) {
res.writeHead(302, { Location: 'https://example.com' });
res.end();
}
A function that redirects requests to another URL.
7
Vercel Function with Custom Headers
# vercel/demo/headers.js
export default function handler(req, res) {
res.setHeader('X-Custom-Header', 'VercelFunction');
res.status(200).send('Custom headers added');
}
A function that adds custom headers to the response.
8
Vercel Function Fetching External API
# vercel/demo/fetch.js
export default async function handler(req, res) {
const response = await fetch('https://api.github.com');
const data = await response.json();
res.status(200).json(data);
}
A function fetching data from an external API and returning it.
9
Vercel Function Serving HTML
# vercel/demo/html.js
export default function handler(req, res) {
const html = '<!DOCTYPE html><html><body><h1>Hello HTML!</h1></body></html>';
res.setHeader('Content-Type', 'text/html');
res.status(200).send(html);
}
A function that responds with a simple HTML page.
10
Vercel Function Conditional Response
# vercel/demo/method.js
export default function handler(req, res) {
if (req.method === 'POST') {
res.status(200).send('You sent a POST request');
} else {
res.status(200).send('You sent a GET request');
}
}
A function that responds differently based on the HTTP method.