{"slug": "ai-built-a-url-shortener-in-seconds-would-you-ship-it", "title": "AI Built a URL Shortener in Seconds. Would You Ship It?", "summary": "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.", "body_md": "Vibe Coding vs. Real Programming — One Real Project, Two Very Different Approaches.\n\nImagine building your own version of Bitly.\n\nA user pastes a long URL, clicks a button, and gets a short link.\n\nFor example:\n\nOriginal URL:\n\n```\n https://example.com/blog/how-to-learn-programming-in-2026\n```\n\nShort URL:\n\n```\n  https://short.ly/a8f92b\n```\n\nSimple, right?\n\nNow imagine opening an AI coding assistant and typing:\n\n\"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.\"\n\nA few seconds later, AI generates the code.\n\nYou run it.\n\nIt works.\n\nCongratulations! You've built a URL shortener.\n\nBut here's a question:\n\nWould you actually deploy that code for real users?\n\nThis is where the difference between Vibe Coding and Programming becomes interesting.\n\nLet's build the same application twice, compare the code, and discover what separates a working prototype from reliable software.\n\nVibe 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.\n\nInstead of manually writing every function, you focus on communicating your ideas.\n\n\"Build me a login page.\"\n\n\"Connect this application to a database.\"\n\n\"Add a payment system.\"\n\n\"Fix this error.\"\n\n\"Make the dashboard responsive.\"\n\nAI handles much of the code generation.\n\nYou test the result, give feedback, and ask AI to improve it.\n\nIt's an exciting way to turn ideas into working prototypes, especially for beginners.\n\nHowever, there is an important distinction between using AI to generate code and blindly accepting code you don't understand.\n\nThe latter is where problems begin.\n\nLet's imagine a quick AI-generated prototype.\n\nA simplified implementation might look like this:\n\n``` js\nconst links = new Map<string, string>();\n\napp.post(\"/api/links\", (req, res) => {\n  const code = Math.random()\n    .toString(36)\n    .slice(2, 8);\n\n  links.set(code, req.body.url);\n\n  res.status(201).json({\n    shortUrl: `http://localhost:3000/${code}`\n  });\n});\n\napp.get(\"/:code\", (req, res) => {\n  const destination = links.get(req.params.code);\n\n  if (!destination) {\n    return res.sendStatus(404);\n  }\n\n  return res.redirect(destination);\n});\n```\n\nThat's it.\n\nA few lines of JavaScript create a basic URL shortener.\n\nYou can submit a URL, receive a short link, and redirect visitors to the original destination.\n\nThis is the magic of Vibe Coding.\n\nYou don't need to understand every implementation detail before getting something working.\n\nBut let's examine the code.\n\nFive problems hiding in this implementation\n\nWe're using a JavaScript Map to store links.\n\nRestart the server, and all shortened links disappear.\n\nWhat happens if someone submits an invalid URL?\n\nThe application doesn't properly check the input.\n\nThe generated codes have no reliable collision-handling strategy.\n\nTwo links could potentially receive the same code.\n\nDatabase failures, unexpected requests, and other errors aren't properly handled.\n\nA public URL shortener can be abused to distribute phishing links or spam.\n\nThe implementation doesn't address these risks.\n\nThe application works, but working is not the same as being reliable.\n\nAnd this is exactly where a programmer starts thinking differently.\n\nA programmer doesn't just ask:\n\n\"How can I make this feature work?\"\n\nThey also ask:\n\nWhat happens when the input is invalid?\n\nWhere should the data be stored?\n\nHow do we guarantee unique short codes?\n\nWhat happens when the server restarts?\n\nHow should missing links be handled?\n\nHow can we prevent abuse?\n\nHow can we test the implementation?\n\nBefore writing code, let's define our requirements.\n\nFeature\n\nRequirement\n\nCreate short links\n\nAccept a destination URL\n\nInput validation\n\nAccept only HTTP and HTTPS URLs\n\nPersistent storage\n\nStore links in SQLite\n\nUnique identifiers\n\nGenerate cryptographically random codes\n\nRedirect\n\nReturn an HTTP 302 response\n\nError handling\n\nReturn meaningful HTTP errors\n\nMaintainability\n\nKeep the implementation understandable\n\nNow let's build it.\n\nWe'll use:\n\nNode.js\n\nTypeScript\n\nExpress.js\n\nSQLite\n\nZod\n\nStep 1: Create the Project\n\nOpen your terminal:\n\n```\nmkdir url-shortener\ncd url-shortener\n\nnpm init -y\n\nnpm install express better-sqlite3 zod\n\nnpm install -D typescript tsx @types/node @types/express @types/better-sqlite3\n```\n\nCreate a tsconfig.json file:\n\n`{`\n\n  \"compilerOptions\": {\n\n    \"target\": \"ES2022\",\n\n    \"module\": \"CommonJS\",\n\n    \"moduleResolution\": \"Node\",\n\n    \"strict\": true,\n\n    \"esModuleInterop\": true,\n\n    \"skipLibCheck\": true\n\n  }\n\n}\n\nOur project will contain:\n\n```\nurl-shortener/\n│\n├── app.ts\n├── tsconfig.json\n├── package.json\n└── links.db       (created automatically)\n```\n\nStep 2: Set Up Persistent Storage\n\nIn our first implementation, links were stored in memory.\n\nThis time, we'll use SQLite.\n\nAdd the following code to app.ts:\n\n``` python\nimport express from \"express\";\nimport type {\n  Request,\n  Response,\n  NextFunction\n} from \"express\";\n\nimport Database from \"better-sqlite3\";\nimport { randomBytes } from \"node:crypto\";\nimport { z } from \"zod\";\n\nconst app = express();\n\napp.use(express.json({\n  limit: \"10kb\"\n}));\n\nconst PORT = Number(process.env.PORT ?? 3000);\n\nconst BASE_URL = (\n  process.env.BASE_URL ??\n  `http://localhost:${PORT}`\n).replace(/\\/+$/, \"\");\n\n// Initialize the database\nconst db = new Database(\"links.db\");\n\ndb.pragma(\"journal_mode = WAL\");\n\ndb.exec(`\n  CREATE TABLE IF NOT EXISTS links (\n    code TEXT PRIMARY KEY,\n    destination TEXT NOT NULL,\n    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP\n  )\n`);\n```\n\nWe now have a database table for storing shortened links.\n\nEach link contains:\n\nA unique code.\n\nThe original destination.\n\nIts creation date.\n\nUnlike a JavaScript Map, this information survives server restarts.\n\nStep 3: Validate User Input\n\nNever blindly trust data submitted by users.\n\nFor our URL shortener, we only want to accept HTTP and HTTPS destinations.\n\nWe'll use Zod:\n\n``` js\nconst shortenSchema = z.object({\n  url: z\n    .string()\n    .trim()\n    .max(2048)\n    .url()\n    .refine((value) => {\n      try {\n        const parsed = new URL(value);\n\n        return (\n          (parsed.protocol === \"http:\" ||\n           parsed.protocol === \"https:\") &&\n          parsed.username === \"\" &&\n          parsed.password === \"\"\n        );\n\n      } catch {\n        return false;\n      }\n    }, \"Only HTTP and HTTPS URLs are allowed.\")\n}).strict();\n```\n\nNow consider this request:\n\n```\n{\n  \"url\": \"javascript:alert(1)\"\n}\n```\n\nIt should be rejected.\n\nWhat about this one?\n\n```\n{\n  \"url\": \"https://example.com\",\n  \"admin\": true\n}\n```\n\nIt should also be rejected because our API doesn't accept unexpected fields.\n\nThis is a small example of an important programming principle:\n\nNever assume that incoming data is valid just because the interface looks correct.\n\nStep 4: Generate Unique Short Codes\n\nWe need a way to generate short identifiers.\n\nInstead of using Math.random(), let's use Node.js's built-in cryptographic random generator.\n\n``` js\nconst insertLink = db.prepare(`\n  INSERT OR IGNORE INTO links (\n    code,\n    destination\n  )\n  VALUES (?, ?)\n`);\n\nfunction createShortCode(destination: string): string {\n\n  for (let attempt = 0; attempt < 5; attempt++) {\n\n    const code = randomBytes(6).toString(\"hex\");\n\n    const result = insertLink.run(\n      code,\n      destination\n    );\n\n    if (result.changes === 1) {\n      return code;\n    }\n  }\n\n  throw new Error(\n    \"Could not generate a unique short code\"\n  );\n}\n```\n\nWhy is this better?\n\nEach identifier contains 12 hexadecimal characters generated from six random bytes.\n\nThe database also enforces uniqueness through its primary key.\n\nIf a collision occurs, the insertion is ignored and the application tries again.\n\nWe are not simply hoping that duplicate codes won't happen.\n\nWe're designing the application to handle that possibility.\n\nStep 5: Create the Shortening API\n\nNow let's build the endpoint.\n\n``` js\napp.post(\n  \"/api/links\",\n  (req: Request, res: Response, next: NextFunction) => {\n\n    const result = shortenSchema.safeParse(req.body);\n\n    if (!result.success) {\n      return res.status(400).json({\n        error: \"Invalid URL\",\n        details: result.error.flatten()\n      });\n    }\n\n    try {\n      const code = createShortCode(result.data.url);\n\n      return res.status(201).json({\n        code,\n        shortUrl: `${BASE_URL}/${code}`\n      });\n\n    } catch (error) {\n      return next(error);\n    }\n  }\n);\n```\n\nThis endpoint:\n\nReceives the URL.\n\nValidates the input.\n\nGenerates a unique code.\n\nStores the link in SQLite.\n\nReturns the shortened URL.\n\nNotice that validation happens before database insertion.\n\nThat's an important difference from our first implementation.\n\nStep 6: Implement the Redirect Feature\n\nNow we need to make shortened links work.\n\n```\n embed http://localhost:3000/a8f92b7c41d2\n```\n\nShould redirect users to the original destination.\n\nLet's implement that:\n\n``` js\nconst findLink = db.prepare(`\n  SELECT destination\n  FROM links\n  WHERE code = ?\n`);\n\napp.get(\"/:code\", (req, res) => {\n\n  const code = req.params.code;\n\n  if (!/^[a-f0-9]{12}$/i.test(code)) {\n    return res.status(404).json({\n      error: \"Link not found\"\n    });\n  }\n\n  const link = findLink.get(code) as\n    | { destination: string }\n    | undefined;\n\n  if (!link) {\n    return res.status(404).json({\n      error: \"Link not found\"\n    });\n  }\n\n  return res.redirect(302, link.destination);\n});\n```\n\nThis code checks whether the short code exists.\n\nIf it exists, the user receives an HTTP 302 redirect.\n\nIf it doesn't exist, the API returns a 404 response.\n\nStep 7: Add Centralized Error Handling\n\nA good application should handle unexpected errors gracefully.\n\nLet's add a centralized error handler:\n\n```\napp.use((\n  error: unknown,\n  _req: Request,\n  res: Response,\n  _next: NextFunction\n) => {\n\n  console.error(error);\n\n  return res.status(500).json({\n    error: \"Internal server error\"\n  });\n});\n```\n\nFinally, start the server:\n\n``` js\napp.listen(PORT, () => {\n  console.log(\n    `URL Shortener running at ${BASE_URL}`\n  );\n});\n```\n\nOur app.ts now contains the complete implementation.\n\nRun it:\n\n```\nnpx tsx app.ts\n```\n\nFor a real deployment, configure BASE_URL to your actual domain.\n\nLet's see whether everything works.\n\nCreate a Short Link\n\nRun:\n\n```\ncurl -X POST http://localhost:3000/api/links \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"url\":\"https://dev.to\"}'\n```\n\nExample response:\n\n{\n\n  \"code\": \"a8f92b7c41d2\",\n\n  \"shortUrl\": \"[http://localhost:3000/a8f92b7c41d2](http://localhost:3000/a8f92b7c41d2)\"\n\n}\n\nWe've successfully created our first short link.\n\nTest the Redirect\n\nOpen the returned URL in your browser.\n\nOr run:\n\n```\ncurl -i http://localhost:3000/a8f92b7c41d2\n```\n\nYou should receive an HTTP 302 response with a Location header pointing to [https://dev.to](https://dev.to).\n\nTest an Invalid URL\n\n```\ncurl -X POST http://localhost:3000/api/links \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"url\":\"javascript:alert(1)\"}'\n```\n\nThe application should return HTTP 400.\n\nTest a Missing Link\n\n```\ncurl -i http://localhost:3000/unknown\n```\n\nThe application should return HTTP 404.\n\nThat's the difference between writing code that works in a quick demonstration and deliberately handling different application scenarios.\n\nLet's put the two versions side by side.\n\nCategory\n\nQuick AI Prototype\n\nEngineering Approach\n\nCode generation\n\nVery fast\n\nDeliberate implementation\n\nStorage\n\nIn-memory Map\n\nMissing\n\nUnique codes\n\nBasic random generation\n\nCryptographic randomness + DB constraint\n\nCollision handling\n\nRetry mechanism\n\nMissing links\n\nBasic handling\n\nExplicit 404\n\nLimited\n\nCentralized\n\nTesting\n\nQuick manual check\n\nDefined test scenarios\n\nProduction preparation\n\nIncomplete\n\nBetter foundation\n\nThe second implementation isn't automatically production-ready.\n\nA public URL-shortening service also needs rate limiting, abuse reporting, phishing protection, monitoring, and an appropriate hosting and database strategy.\n\nBut we now have a much better foundation.\n\nAnd more importantly, we understand why each part exists.\n\nHere's the important distinction.\n\nA person using Vibe Coding might ask:\n\n\"Build me a URL shortener.\"\n\nA programmer might ask:\n\n\"Build me a URL shortener, validate the destination, handle database failures, prevent identifier collisions, define error responses, and make the implementation testable.\"\n\nBoth can use exactly the same AI tools.\n\nBoth can generate code.\n\nBut the second person is thinking about the behavior of the entire system, not just the immediate result.\n\nVibe Coding is about expressing an idea and accelerating implementation. Programming is about understanding and engineering the solution.\n\nAnd they're not enemies.\n\nA professional programmer can absolutely use Vibe Coding to build prototypes, explore ideas, and accelerate repetitive tasks.\n\nThe real problem isn't using AI.\n\nIt's accepting code without understanding its consequences.\n\nAbsolutely.\n\nBut only when you use it as a tool for learning and problem-solving.\n\nFor example, while building this URL shortener, you could ask an AI coding assistant:\n\nWhy should I use SQLite instead of a JavaScript Map?\n\nWhy is Math.random() not ideal for generating identifiers?\n\nWhat happens when two requests generate the same code?\n\nWhat security issues should I consider?\n\nHow can I write automated tests for this application?\n\nWhat changes would be required to support thousands of users?\n\nThese questions help you understand the engineering decisions behind the code.\n\nYou aren't just asking AI to build something.\n\nYou're using AI to understand how software works.\n\nFor developers who want to build broader AI literacy beyond coding, LearnAiMind is also a useful place to explore AI tools, concepts, and practical applications.\n\nThe goal shouldn't be to become someone who can only build applications by writing prompts.\n\nIt should be to become someone who knows how to use AI effectively and understand the technology behind the results.\n\nI don't think the future of software development is simply AI versus programmers.\n\nIt's more interesting than that.\n\nAI can generate code faster, explain complicated functions, suggest solutions, and automate repetitive tasks.\n\nBut software still needs people who can evaluate requirements, understand architecture, identify risks, verify results, and take responsibility for the systems they build.\n\nThe best developers will not necessarily be the ones who write every line manually.\n\nThey 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.\n\nFinal Thoughts\n\nRemember our URL shortener?\n\nThe first version took only a few lines of code.\n\nThe second version required more thought, validation, storage design, and error handling.\n\nBoth versions demonstrate how quickly AI can turn an idea into software.\n\nBut they also reveal an important lesson:\n\nCreating working code is becoming easier. Understanding and engineering reliable software is still a valuable skill.\n\nDon't just learn how to ask AI to build an application.\n\nLearn how to understand, evaluate, test, and improve the application it builds.\n\nBecause the future doesn't belong only to people who can write code.\n\nIt belongs to people who know what to do with it.\n\nTry This Challenge\n\nTake our first URL shortener implementation and ask your favorite AI coding assistant to improve it.\n\nDon't simply say:\n\n\"Make this code better.\"\n\nInstead, ask:\n\nWhat security vulnerabilities can you identify?\n\nWhat happens when the database becomes unavailable?\n\nHow can we prevent malicious link abuse?\n\nWhat edge cases are missing?\n\nWhich automated tests should be written?\n\nWhat would need to change before production deployment?\n\nThen compare the suggestions with the engineering approach in this article.\n\nYou'll discover that one of the most valuable programming skills isn't generating code.\n\nIt's knowing what questions to ask about the code.\n\nWhat do you think?\n\nWould you trust an AI-generated URL shortener and deploy it immediately, or would you review and test every important part first?\n\nHave you ever built an application using Vibe Coding?\n\nShare your experience in the comments!", "url": "https://wpnews.pro/news/ai-built-a-url-shortener-in-seconds-would-you-ship-it", "canonical_source": "https://dev.to/ai_topics/ai-built-a-url-shortener-in-seconds-would-you-ship-it-31l2", "published_at": "2026-11-18 19:09:19+00:00", "updated_at": "2026-11-18 19:11:59.210072+00:00", "lang": "en", "topics": ["ai-tools", "developer-tools", "artificial-intelligence"], "entities": [], "also_reported_by": [], "takeaway": "AI-generated prototypes typically omit persistence, input validation, collision-safe ID generation and abuse controls, so treat generated code as a starting point and add SQLite storage, HTTP/HTTPS-only validation and cryptographically random short codes before deploying.", "recommendation": {"advice": "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.", "playbook": "coding-agents", "playbook_url": "https://wpnews.pro/playbooks/coding-agents"}, "alternates": {"html": "https://wpnews.pro/news/ai-built-a-url-shortener-in-seconds-would-you-ship-it", "markdown": "https://wpnews.pro/news/ai-built-a-url-shortener-in-seconds-would-you-ship-it.md", "text": "https://wpnews.pro/news/ai-built-a-url-shortener-in-seconds-would-you-ship-it.txt", "jsonld": "https://wpnews.pro/news/ai-built-a-url-shortener-in-seconds-would-you-ship-it.jsonld"}}