Dev.to WebDev 🛠 Dev 👁 0 📖 7 min read

What Is a Serverless Backend? A Simple Explanation, Example, and Starter Server 🚀

You build a small app. It works great on your laptop. Then someone asks, "Cool, where is it hosted?" and suddenly you're reading about servers, ports, uptime, and updates when you just wanted to ship a feature. 😅 That's

You build a small app. It works great on your laptop. Then someone asks, "Cool, where is it hosted?" and suddenly you're reading about servers, ports, uptime, and updates when you just wanted to ship a feature. 😅

That's the moment many developers first hear about a serverless backend.

The name sounds like magic, as if the servers vanished. They didn't. So what does serverless actually mean, and how can you build a small one today? Let's find out. 😊

What Is a Serverless Backend?

A serverless backend is a backend where you write your code as small functions, and a cloud provider runs them for you only when they're needed.

Servers still exist. You just don't set them up, patch them, or keep them running. The provider handles that.

A simple analogy 🍕

Imagine you want pizza.

  • Traditional server: You rent a whole kitchen and a chef. They wait around all day, even when nobody orders. You pay for the kitchen either way.
  • Serverless: You order from a pizza place. The kitchen starts working when your order arrives, and you pay for that order.

In serverless, your "order" is a request, like someone opening your app or submitting a form. Your function wakes up, does its job, sends the response, and goes back to sleep.

Where you'll see this

Several platforms offer this model, including AWS Lambda, Vercel Functions, Netlify Functions, and Cloudflare Workers. The details differ, but the idea is the same: you write a function, they run it on demand.

You'll also hear the term FaaS (Functions as a Service). It's the part of serverless that deals with running your functions.

Why Serverless Backends Matter

Here's why it's worth learning:

  • Less setup. You can go from idea to a working API quickly, without configuring a machine first.
  • Less maintenance. The provider handles the underlying servers, so you spend more time on your actual product.
  • Good for learning. Students and beginners can build real APIs without learning server administration first.
  • Common in modern stacks. If you use a framework like Next.js, you may already be writing serverless-style API routes without calling them that.

It won't replace every kind of backend. But it's a useful tool to have.

Benefits of Serverless (With Real-Life Examples)

  1. You pay for what you use (on most platforms)
    Many providers bill based on usage, such as the number of requests and how long your code runs, and often include a free tier. Example: a small portfolio contact form that gets a few messages a week doesn't need a machine running 24/7. Always check the current pricing of your provider, since it changes.

  2. No server maintenance
    You don't manage operating system updates or server patches. Example: instead of fixing a server at 2 a.m., you push code and move on.

  3. Scaling is handled for you
    If more people visit, the platform can run more copies of your function. Example: a newsletter signup endpoint shouldn't need a rewrite just because a post got shared more than usual. Platforms have limits and settings, so read their docs.

  4. Fast to start
    A small function is often just one file. Example: a "send a thank-you email" function can be live the same afternoon you write it.

  5. Great for small, focused jobs
    Example: resizing an uploaded image, validating a form, or receiving a webhook from a payment service.

Serverless vs Traditional Server: A Quick Comparison

Neither is "better" in every case. They fit different situations.

Traditional Server Serverless Backend
Setup You configure and manage the machine Provider manages the infrastructure
Running Always on Runs when a request arrives
Billing Usually fixed or reserved capacity Usually based on usage
State Can keep things in memory Don't rely on memory between requests
Long tasks Comfortable Often limited by execution time
Best for Steady traffic, long-running work Small APIs, bursts of traffic, quick jobs

Honest nuance: serverless functions can have a short delay on the first request after being idle. This is commonly called a cold start. For many apps it's barely noticeable, but it's good to know it exists.

Let's Build a Tiny Serverless Backend 🔧

Since this blog should be practical, here's a small starter you can run today.

We'll use a Next.js Route Handler. On platforms like Vercel, route handlers can run as serverless functions. We'll build two endpoints:

  • GET /api/hello returns a greeting
  • POST /api/subscribe validates an email and responds

Step 1: Create a Next.js project

pnpm create next-app@latest my-serverless-api
cd my-serverless-api

Pick TypeScript and the App Router when asked. (You can use npm or yarn too.)

Step 2: Create your first function

Create this file: app/api/hello/route.ts

import { NextResponse } from "next/server";

// GET /api/hello?name=Sara
export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const name = searchParams.get("name") ?? "friend";

  return NextResponse.json({
    message: `Hello, ${name}! 👋`,
    time: new Date().toISOString(),
  });
}

That's a working backend endpoint. No server setup. No port configuration in your code.

Step 3: Add a POST endpoint

Create: app/api/subscribe/route.ts

import { NextResponse } from "next/server";

// POST /api/subscribe
export async function POST(request: Request) {
  // If the body isn't valid JSON, treat it as empty
  const body = await request.json().catch(() => null);

  const email = body?.email;

  if (typeof email !== "string" || !email.includes("@")) {
    return NextResponse.json(
      { error: "Please send a valid email." },
      { status: 400 }
    );
  }

  // In a real app, save the email to a database or email service here.
  return NextResponse.json(
    { ok: true, message: `Thanks! We'll write to ${email}.` },
    { status: 201 }
  );
}

Notice the comment inside the function. We're not storing the email in a variable that lives between requests. In serverless, that wouldn't be reliable. Real data belongs in a database. More on that below.

Step 4: Run it locally

pnpm dev

Then test it:

# GET request
curl "http://localhost:3000/api/hello?name=Sara"

# POST request
curl -X POST http://localhost:3000/api/subscribe \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]"}'

You should see JSON responses for both. 🎉

Step 5: Deploy it

One simple way is to push your project to GitHub and import it into Vercel. Your route handlers get deployed as serverless functions. You can also use the Vercel CLI if you prefer the terminal.

Other hosts work too. Just check how each one supports Next.js route handlers.

Not using Next.js? Here's a plain AWS Lambda version

The idea is the same: a function that receives an event and returns a response.

// index.mjs
export const handler = async (event) => {
  const name = event.queryStringParameters?.name ?? "friend";

  return {
    statusCode: 200,
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ message: `Hello, ${name}!` }),
  };
};

On AWS, you'd connect this function to an HTTP endpoint (for example, using API Gateway or a Lambda function URL). Setup steps vary, so follow the current AWS docs.

Best Tips and Do's & Don'ts ✅

Do:

  • Keep functions small and focused. One function, one job.
  • Store data in a database or storage service. Don't rely on memory between requests.
  • Validate input. Never trust whatever the client sends.
  • Use environment variables for secrets. API keys should never sit in your code.
  • Check your provider's limits. Timeouts, payload sizes, and memory limits differ between platforms.
  • Log useful information. It makes debugging much easier when you can't "look inside" the server.

Don't:

  • Don't put secrets in your repo. Not even "just for testing."
  • Don't run very long jobs in a single function unless your platform clearly supports it.
  • Don't assume local behavior equals production behavior. Test after deploying.

Common Mistakes People Make

1. Thinking "serverless" means "no servers"

Servers exist. You just don't manage them. Knowing this helps you understand limits like timeouts and cold starts.

2. Saving data in a variable and expecting it to stay

This is a classic. It seems to work on your machine, then data disappears in production. Why? Your function may run in different instances, and instances can start and stop. Fix: use a database.

3. Ignoring cold starts

The first request after a quiet period can be a little slower. Fix: keep functions lightweight, and measure before worrying.

4. Forgetting about timeouts

Functions usually have a maximum run time. A heavy job that works locally might get cut off. Fix: check your provider's limits and break big jobs into smaller pieces.

5. Skipping input validation

It's tempting to trust the request body. Don't. Fix: validate everything, like we did with the email check above.

6. Hardcoding secrets

It happens when we're in a hurry. Fix: use environment variables from day one.

7. Choosing serverless for everything

It's a great fit for many things, but not all. Fix: pick the tool that fits the job, not the one that's trending.

Conclusion

A serverless backend lets you write small functions and let a cloud provider run them when needed. You skip much of the server management, start quickly, and focus on building features.

To recap:

  • Servers still exist, you just don't manage them.
  • Functions run on demand, and billing is often based on usage.
  • Don't store important data in memory. Use a database.
  • Watch out for cold starts, timeouts, and provider limits.
  • It's a great way to build small APIs, forms, and webhooks.

You've already seen how little code a working serverless backend takes. Try the starter above, change the message, add a field, and make it yours. 😊

If this post helped, you can read more developer-friendly articles on hamidrazadev.com. And if you know someone who's curious about serverless, share it with them. 🚀

Got questions, or want to share what you built? Drop a comment. I'd love to hear how it goes!

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.