Getting Started with Serverless Functions
🎯 Introduction
Frontend projects often need backend APIs. Does that mean renting a server and learning another language? In this article, you will use serverless functions to write deployable backend endpoints in the same project, using familiar JavaScript.
🧱 What Is a Serverless Function?
A serverless function is a function that runs in the cloud, with an endpoint URL for each function.
You do not need to rent a server, install a runtime, or manage operations. Write a function file, and Vercel turns it into an accessible API.
Think of a traditional backend as opening a restaurant: you rent premises, fit them out, and hire staff to keep it running all day. A serverless function is like a shared kitchen: work starts when an order arrives, with no idle cost when there are no orders.
🛠 Your First Endpoint
Create an api folder in the project root. Each file inside automatically becomes an endpoint. Create api/hello.js:
export default function handler(request, response) {
response.status(200).json({
message: 'Hello from Serverless!',
time: new Date().toLocaleString()
});
}
The rules are simple:
- File path
api/hello.js→ endpoint/api/hello. - Use
export defaultto export a function acceptingrequestandresponse. - Return JSON with
response.status(200).json(...).
After deploying, visit https://your-domain/api/hello to see the JSON response.
💻 Local Testing with vercel dev
The Vite server started by npm run dev does not handle the api directory. To test endpoints locally, use this Vercel CLI command:
vercel dev
It starts both the frontend project and serverless functions, simulating the deployed environment. Open http://localhost:3000/api/hello to test your endpoint locally.
vercel dev also loads the Development environment variables configured in the dashboard, helping keep local and deployed behavior consistent.💡 A Common Use Case: Keeping Secrets on the Server
As discussed in article 3, variables prefixed with VITE_ are exposed in frontend code and must not contain secrets. Instead, move calls to third-party APIs into a serverless function:
export default async function handler(request, response) {
// Store the key in Vercel environment variables; it stays on the server
const key = process.env.WEATHER_API_KEY;
const res = await fetch(`https://api.example.com/weather?key=${key}&city=beijing`);
const data = await res.json();
response.status(200).json(data);
}
The frontend only calls your own /api/weather endpoint. The key stays on the server. This API proxy pattern is one of the most common uses of serverless functions in frontend projects.
❓ Knowledge Check
Q1: Can I write serverless functions in TypeScript?
Yes. Rename the file to api/hello.ts and add parameter types. Vercel compiles it automatically.
Q2: Is function code bundled into the frontend output?
No. Code in api runs only on Vercel's servers. Visitors cannot directly view its source.
Q3: Can an endpoint accept POST requests?
Yes. Check request.method for the HTTP method and read submitted data from request.body.
Q4: Can a serverless function connect to a database?
Yes. Functions run in a regular Node.js environment, so you can install database clients for MySQL, MongoDB, and others. Databases are covered in Stage7; for now, understanding the idea is enough.
🧪 Practice
- Create
api/time.jsto return the current server time and a random lucky number. - Test the endpoint locally with
vercel dev, then deploy it and verify the live response. - Call it from the homepage with
fetch('/api/time')and display the result.
// Write your code here
🎉 You now understand serverless functions and have completed the Vercel course! You can take a frontend project from a local starting point to a live deployment.
