cd /news/ai-tools/ai-built-a-url-shortener-in-seconds-… · home › topics › ai-tools › article
[ARTICLE · art-172031] src=dev.to ↗ pub= topic=ai-tools verified=true sentiment=· neutral

AI Built a URL Shortener in Seconds. Would You Ship It?

A developer compared an AI-generated URL shortener prototype against a production-grade implementation, showing that the vibe-coded version stores links in an in-memory Map, skips URL validation, uses Math.random for short codes without collision handling, and ignores abuse prevention. The rewrite adds SQLite persistence, HTTP/HTTPS-only input validation, and cryptographically random identifiers, arguing that working code is not the same as reliable software.

recommendation

Review AI-generated code for persistence, input validation, unique ID generation and abuse prevention before shipping; the source's Map-based prototype lost all links on restart and used Math.random codes.

more in playbook: Working with AI coding agents
by read11 min views1 publishedNov 18, 2026

Vibe Coding vs. Real Programming — One Real Project, Two Very Different Approaches.

Imagine building your own version of Bitly.

A user pastes a long URL, clicks a button, and gets a short link.

For example:

Original URL:

 https://example.com/blog/how-to-learn-programming-in-2026

Short URL:

  https://short.ly/a8f92b

Simple, right?

Now imagine opening an AI coding assistant and typing:

"Build me a URL shortener using Node.js and Express. Users should be able to submit a URL and receive a shortened link. When someone visits the shortened link, redirect them to the original URL."

A few seconds later, AI generates the code.

You run it.

It works.

Congratulations! You've built a URL shortener.

But here's a question:

Would you actually deploy that code for real users?

This is where the difference between Vibe Coding and Programming becomes interesting.

Let's build the same application twice, compare the code, and discover what separates a working prototype from reliable software.

Vibe Coding is an AI-driven approach to software development in which you describe what you want using natural language and let AI generate much of the implementation.

Instead of manually writing every function, you focus on communicating your ideas.

"Build me a login page."

"Connect this application to a database."

"Add a payment system."

"Fix this error."

"Make the dashboard responsive."

AI handles much of the code generation.

You test the result, give feedback, and ask AI to improve it.

It's an exciting way to turn ideas into working prototypes, especially for beginners.

However, there is an important distinction between using AI to generate code and blindly accepting code you don't understand.

The latter is where problems begin.

Let's imagine a quick AI-generated prototype.

A simplified implementation might look like this:

const links = new Map<string, string>();

app.post("/api/links", (req, res) => {
  const code = Math.random()
    .toString(36)
    .slice(2, 8);

  links.set(code, req.body.url);

  res.status(201).json({
    shortUrl: `http://localhost:3000/${code}`
  });
});

app.get("/:code", (req, res) => {
  const destination = links.get(req.params.code);

  if (!destination) {
    return res.sendStatus(404);
  }

  return res.redirect(destination);
});

That's it.

A few lines of JavaScript create a basic URL shortener.

You can submit a URL, receive a short link, and redirect visitors to the original destination.

This is the magic of Vibe Coding.

You don't need to understand every implementation detail before getting something working.

But let's examine the code.

Five problems hiding in this implementation

We're using a JavaScript Map to store links.

Restart the server, and all shortened links disappear.

What happens if someone submits an invalid URL?

The application doesn't properly check the input.

The generated codes have no reliable collision-handling strategy.

Two links could potentially receive the same code.

Database failures, unexpected requests, and other errors aren't properly handled.

A public URL shortener can be abused to distribute phishing links or spam.

The implementation doesn't address these risks.

The application works, but working is not the same as being reliable.

And this is exactly where a programmer starts thinking differently.

A programmer doesn't just ask:

"How can I make this feature work?"

They also ask:

What happens when the input is invalid?

Where should the data be stored?

How do we guarantee unique short codes?

What happens when the server restarts?

How should missing links be handled?

How can we prevent abuse?

How can we test the implementation?

Before writing code, let's define our requirements.

Feature

Requirement

Create short links

Accept a destination URL

Input validation

Accept only HTTP and HTTPS URLs

Persistent storage

Store links in SQLite

Unique identifiers

Generate cryptographically random codes

Redirect

Return an HTTP 302 response

Error handling

Return meaningful HTTP errors

Maintainability

Keep the implementation understandable

Now let's build it.

We'll use:

Node.js

TypeScript

Express.js

SQLite

Zod

Step 1: Create the Project

Open your terminal:

mkdir url-shortener
cd url-shortener

npm init -y

npm install express better-sqlite3 zod

npm install -D typescript tsx @types/node @types/express @types/better-sqlite3

Create a tsconfig.json file:

{

"compilerOptions": {

"target": "ES2022",

"module": "CommonJS",

"moduleResolution": "Node",

"strict": true,

"esModuleInterop": true,

"skipLibCheck": true

}

}

Our project will contain:

url-shortener/
│
├── app.ts
├── tsconfig.json
├── package.json
└── links.db       (created automatically)

Step 2: Set Up Persistent Storage

In our first implementation, links were stored in memory.

This time, we'll use SQLite.

Add the following code to app.ts:

import express from "express";
import type {
  Request,
  Response,
  NextFunction
} from "express";

import Database from "better-sqlite3";
import { randomBytes } from "node:crypto";
import { z } from "zod";

const app = express();

app.use(express.json({
  limit: "10kb"
}));

const PORT = Number(process.env.PORT ?? 3000);

const BASE_URL = (
  process.env.BASE_URL ??
  `http://localhost:${PORT}`
).replace(/\/+$/, "");

// Initialize the database
const db = new Database("links.db");

db.pragma("journal_mode = WAL");

db.exec(`
  CREATE TABLE IF NOT EXISTS links (
    code TEXT PRIMARY KEY,
    destination TEXT NOT NULL,
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
  )
`);

We now have a database table for storing shortened links.

Each link contains:

A unique code.

The original destination.

Its creation date.

Unlike a JavaScript Map, this information survives server restarts.

Step 3: Validate User Input

Never blindly trust data submitted by users.

For our URL shortener, we only want to accept HTTP and HTTPS destinations.

We'll use Zod:

const shortenSchema = z.object({
  url: z
    .string()
    .trim()
    .max(2048)
    .url()
    .refine((value) => {
      try {
        const parsed = new URL(value);

        return (
          (parsed.protocol === "http:" ||
           parsed.protocol === "https:") &&
          parsed.username === "" &&
          parsed.password === ""
        );

      } catch {
        return false;
      }
    }, "Only HTTP and HTTPS URLs are allowed.")
}).strict();

Now consider this request:

{
  "url": "javascript:alert(1)"
}

It should be rejected.

What about this one?

{
  "url": "https://example.com",
  "admin": true
}

It should also be rejected because our API doesn't accept unexpected fields.

This is a small example of an important programming principle:

Never assume that incoming data is valid just because the interface looks correct.

Step 4: Generate Unique Short Codes

We need a way to generate short identifiers.

Instead of using Math.random(), let's use Node.js's built-in cryptographic random generator.

const insertLink = db.prepare(`
  INSERT OR IGNORE INTO links (
    code,
    destination
  )
  VALUES (?, ?)
`);

function createShortCode(destination: string): string {

  for (let attempt = 0; attempt < 5; attempt++) {

    const code = randomBytes(6).toString("hex");

    const result = insertLink.run(
      code,
      destination
    );

    if (result.changes === 1) {
      return code;
    }
  }

  throw new Error(
    "Could not generate a unique short code"
  );
}

Why is this better?

Each identifier contains 12 hexadecimal characters generated from six random bytes.

The database also enforces uniqueness through its primary key.

If a collision occurs, the insertion is ignored and the application tries again.

We are not simply hoping that duplicate codes won't happen.

We're designing the application to handle that possibility.

Step 5: Create the Shortening API

Now let's build the endpoint.

app.post(
  "/api/links",
  (req: Request, res: Response, next: NextFunction) => {

    const result = shortenSchema.safeParse(req.body);

    if (!result.success) {
      return res.status(400).json({
        error: "Invalid URL",
        details: result.error.flatten()
      });
    }

    try {
      const code = createShortCode(result.data.url);

      return res.status(201).json({
        code,
        shortUrl: `${BASE_URL}/${code}`
      });

    } catch (error) {
      return next(error);
    }
  }
);

This endpoint:

Receives the URL.

Validates the input.

Generates a unique code.

Stores the link in SQLite.

Returns the shortened URL.

Notice that validation happens before database insertion.

That's an important difference from our first implementation.

Step 6: Implement the Redirect Feature

Now we need to make shortened links work.

 embed http://localhost:3000/a8f92b7c41d2

Should redirect users to the original destination.

Let's implement that:

const findLink = db.prepare(`
  SELECT destination
  FROM links
  WHERE code = ?
`);

app.get("/:code", (req, res) => {

  const code = req.params.code;

  if (!/^[a-f0-9]{12}$/i.test(code)) {
    return res.status(404).json({
      error: "Link not found"
    });
  }

  const link = findLink.get(code) as
    | { destination: string }
    | undefined;

  if (!link) {
    return res.status(404).json({
      error: "Link not found"
    });
  }

  return res.redirect(302, link.destination);
});

This code checks whether the short code exists.

If it exists, the user receives an HTTP 302 redirect.

If it doesn't exist, the API returns a 404 response.

Step 7: Add Centralized Error Handling

A good application should handle unexpected errors gracefully.

Let's add a centralized error handler:

app.use((
  error: unknown,
  _req: Request,
  res: Response,
  _next: NextFunction
) => {

  console.error(error);

  return res.status(500).json({
    error: "Internal server error"
  });
});

Finally, start the server:

app.listen(PORT, () => {
  console.log(
    `URL Shortener running at ${BASE_URL}`
  );
});

Our app.ts now contains the complete implementation.

Run it:

npx tsx app.ts

For a real deployment, configure BASE_URL to your actual domain.

Let's see whether everything works.

Create a Short Link

Run:

curl -X POST http://localhost:3000/api/links \
  -H "Content-Type: application/json" \
  -d '{"url":"https://dev.to"}'

Example response:

{

"code": "a8f92b7c41d2",

"shortUrl": "http://localhost:3000/a8f92b7c41d2"

}

We've successfully created our first short link.

Test the Redirect

Open the returned URL in your browser.

Or run:

curl -i http://localhost:3000/a8f92b7c41d2

You should receive an HTTP 302 response with a Location header pointing to https://dev.to.

Test an Invalid URL

curl -X POST http://localhost:3000/api/links \
  -H "Content-Type: application/json" \
  -d '{"url":"javascript:alert(1)"}'

The application should return HTTP 400.

Test a Missing Link

curl -i http://localhost:3000/unknown

The application should return HTTP 404.

That's the difference between writing code that works in a quick demonstration and deliberately handling different application scenarios.

Let's put the two versions side by side.

Category

Quick AI Prototype

Engineering Approach

Code generation

Very fast

Deliberate implementation

Storage

In-memory Map

Missing

Unique codes

Basic random generation

Cryptographic randomness + DB constraint

Collision handling

Retry mechanism

Missing links

Basic handling

Explicit 404

Limited

Centralized

Testing

Quick manual check

Defined test scenarios

Production preparation

Incomplete

Better foundation

The second implementation isn't automatically production-ready.

A public URL-shortening service also needs rate limiting, abuse reporting, phishing protection, monitoring, and an appropriate hosting and database strategy.

But we now have a much better foundation.

And more importantly, we understand why each part exists.

Here's the important distinction.

A person using Vibe Coding might ask:

"Build me a URL shortener."

A programmer might ask:

"Build me a URL shortener, validate the destination, handle database failures, prevent identifier collisions, define error responses, and make the implementation testable."

Both can use exactly the same AI tools.

Both can generate code.

But the second person is thinking about the behavior of the entire system, not just the immediate result.

Vibe Coding is about expressing an idea and accelerating implementation. Programming is about understanding and engineering the solution.

And they're not enemies.

A professional programmer can absolutely use Vibe Coding to build prototypes, explore ideas, and accelerate repetitive tasks.

The real problem isn't using AI.

It's accepting code without understanding its consequences.

Absolutely.

But only when you use it as a tool for learning and problem-solving.

For example, while building this URL shortener, you could ask an AI coding assistant:

Why should I use SQLite instead of a JavaScript Map?

Why is Math.random() not ideal for generating identifiers?

What happens when two requests generate the same code?

What security issues should I consider?

How can I write automated tests for this application?

What changes would be required to support thousands of users?

These questions help you understand the engineering decisions behind the code.

You aren't just asking AI to build something.

You're using AI to understand how software works.

For developers who want to build broader AI literacy beyond coding, LearnAiMind is also a useful place to explore AI tools, concepts, and practical applications.

The goal shouldn't be to become someone who can only build applications by writing prompts.

It should be to become someone who knows how to use AI effectively and understand the technology behind the results.

I don't think the future of software development is simply AI versus programmers.

It's more interesting than that.

AI can generate code faster, explain complicated functions, suggest solutions, and automate repetitive tasks.

But software still needs people who can evaluate requirements, understand architecture, identify risks, verify results, and take responsibility for the systems they build.

The best developers will not necessarily be the ones who write every line manually.

They will be the ones who understand what needs to be built, know how to work with AI, and can recognize when the generated solution is wrong.

Final Thoughts

Remember our URL shortener?

The first version took only a few lines of code.

The second version required more thought, validation, storage design, and error handling.

Both versions demonstrate how quickly AI can turn an idea into software.

But they also reveal an important lesson:

Creating working code is becoming easier. Understanding and engineering reliable software is still a valuable skill.

Don't just learn how to ask AI to build an application.

Learn how to understand, evaluate, test, and improve the application it builds.

Because the future doesn't belong only to people who can write code.

It belongs to people who know what to do with it.

Try This Challenge

Take our first URL shortener implementation and ask your favorite AI coding assistant to improve it.

Don't simply say:

"Make this code better."

Instead, ask:

What security vulnerabilities can you identify?

What happens when the database becomes unavailable?

How can we prevent malicious link abuse?

What edge cases are missing?

Which automated tests should be written?

What would need to change before production deployment?

Then compare the suggestions with the engineering approach in this article.

You'll discover that one of the most valuable programming skills isn't generating code.

It's knowing what questions to ask about the code.

What do you think?

Would you trust an AI-generated URL shortener and deploy it immediately, or would you review and test every important part first?

Have you ever built an application using Vibe Coding?

Share your experience in the comments!

── more in #ai-tools 4 stories · sorted by recency
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/ai-built-a-url-short…] indexed:0 read:11min 2026-11-18 · —