Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 37 ยท Projects and Practice

Project: An API and Database App

Plan a full-stack link shortener on Vercel or Netlify: serverless API routes, a Postgres database, KV rate limiting, environment separation for previews, tests and rollout, with runnable stand-ins.

This project goes beyond static pages: a link shortener with an HTTP API, a database and rate limiting, deployed from Git with separate environments. It uses what you learned about functions, storage, environment variables and previews. The design works on either platform; code files differ slightly in layout.

The platforms and databases cannot run here. The code below is a read-only sketch of real deployment files, while the runnable blocks are JavaScript stand-ins (an in-memory database and handlers) so you can test the logic. Check current package names and APIs before you copy anything.

Requirements

  1. POST /api/links with { "url": "https://..." } creates a short code and returns it.
  2. GET /go/:code redirects (302) to the stored URL and counts the click.
  3. GET /api/links/:code returns the URL and click count.
  4. Reject invalid URLs; limit each IP to a few creations per minute.
  5. Production, preview and local environments use separate data.

Architecture

flowchart LR
  U["Visitor / client"] --> E["CDN edge"]
  E --> F["Serverless functions"]
  F --> K["KV: rate limit counters"]
  F --> D[("Postgres: links table")]
  G["Git push"] --> B["Platform build"]
  B --> F

Functions are stateless: all state lives in KV and Postgres.

Data model

SQL
CREATE TABLE links (
  code       text PRIMARY KEY,
  url        text NOT NULL,
  clicks     integer NOT NULL DEFAULT 0,
  created_at timestamptz NOT NULL DEFAULT now()
);

Use a pooled connection string in functions and a direct one for migrations (Databases from Serverless).

Files (sketch)

On Vercel, route handlers live in api/ (or your framework's route folders); on Netlify, in netlify/functions/:

JavaScript
// api/links.js (read-only sketch)
import { neon } from "@neondatabase/serverless";
const sql = neon(process.env.DATABASE_URL);        // created once per instance

export async function POST(request) {
  const { url } = await request.json();
  // 1. validate  2. rate limit  3. insert with a generated code
  const code = makeCode();
  await sql`INSERT INTO links (code, url) VALUES (${code}, ${url})`;
  return Response.json({ code }, { status: 201 });
}

Environment variables: DATABASE_URL (different value per environment), and the KV credentials. Set them for Production, Preview and Development separately, so a preview cannot touch live data (Preview Deployments).

Build order

Logic first Validate and generate codes.
Data Table and queries.
Limits Rate limit in KV.
Ship Preview, review, promote.

Test the pure logic before deploying.

1 / 2

The core logic as a runnable stand-in

This runs the whole API in memory: URL validation, code generation, creation, lookup, click counting and a fixed-window rate limit. The same functions can later be wired to Postgres and KV.

JS Link shortener stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Testing without deploying

Handlers written as plain functions are easy to test. A tiny assertion helper is enough to keep your behavior from regressing. In a real repository you would use your framework's test runner (Vitest, node:test) in CI before the build.

JS Mini test runner stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Deploying safely

  1. Create the database and add the integration; confirm separate production and preview strings.
  2. Run the migration against a preview database first.
  3. Push a branch and test the API with curl on the preview URL.
  4. Merge; production builds. Smoke-test with one create and one redirect.
  5. If it fails, roll back the code (Rollbacks and Promotions); keep schema changes backward compatible.
  6. Watch function logs and usage (Limits, Quotas and Costs).

Security notes

  • Allow only http and https target URLs; rejecting javascript: and data: prevents injection through redirects.
  • Do not redirect to arbitrary hosts without thought: open redirects help phishers. Consider a block list, or require login to create links.
  • Use parameterized queries only.
  • Add Cache-Control: no-store on counting redirects if exact click counts matter, or accept that CDN-cached redirects will not count every hit.

Extensions

  • Custom codes with uniqueness checks and retry on collision.
  • A small admin page protected by sign-in.
  • Expiry dates enforced with a scheduled function.
  • Analytics by day stored in a second table.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must the database connection string differ between Production and Preview?

    Previews run real code, so isolation prevents accidents.
  2. 2. Why does the rate limit use KV instead of a variable in the function?

    Each instance would keep its own counter, and counters vanish when instances are recycled.
  3. 3. Why reject javascript: URLs?

    Allow only http and https schemes to avoid injection.
  4. 4. Which migration style supports safe rollbacks?

    Backward compatible schema changes let an older deployment keep working.

Summary

  • Serverless apps keep state in a database and KV, never in function memory.
  • Write handler logic as testable plain functions.
  • Isolate environments, run migrations as a deliberate step and test on a preview first.
  • Validate input, parameterize queries and rate-limit public endpoints.
  • Keep schema changes compatible so rollbacks remain safe.

Next: Project: Deploying a Monorepo