/how-to-build-lovable

How to build URL shortener app with Lovable?

Step-by-step guide to build a fast scalable URL shortener app with Lovable. Learn routing, storage, analytics and deployment in one practical tutorial

Book a free  consultation
4.9
Clutch rating 🌟
600+
Happy partners
17+
Countries served
190+
Team members
Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to build URL shortener app with Lovable?

We’ll build a simple URL shortener inside Lovable: a small React SPA that creates short slugs stored in Supabase and a client-side redirect page (r.html?slug=...). You can fully build and preview this in Lovable (no terminal). For production-friendly root-path redirects you’ll export to GitHub and deploy to a host that supports serverless redirects (outside Lovable) — I’ll mark that step clearly.

 

What we’re building / changing

 

A short web app that lets users submit a long URL and get a short slug. The app stores slug→URL in Supabase. Preview in Lovable works using a client-side redirect page (r.html?slug=). For real root-path redirects (example.com/abc) you’ll export to GitHub and deploy to a host that supports serverless functions or rewrite rules.

 

Lovable-native approach

 

  • In Chat Mode ask Lovable to create files (React app + redirect page) and wire Supabase client.
  • Use Preview to test creating links and using r.html?slug=... redirects.
  • Set Secrets in Lovable Cloud (SUPABASE_URL, SUPABASE_KEY) via Secrets UI.
  • When ready, use GitHub export/sync from Lovable to push the repo and deploy externally for root-path redirects or high-availability serverless functions.

 

Meta-prompts to paste into Lovable (paste each as a separate chat message)

 

Prompt 1:
Goal: Create the app scaffold, Supabase client, and UI.
Exact files to create/modify:

  • create index.html
  • create src/index.jsx
  • create src/App.jsx
  • create src/SupabaseClient.js
  • create public/r.html
Acceptance criteria: Done when Preview shows a form to shorten URLs and a list of created links. Clicking a generated link opens public/r.html?slug=THE\_SLUG which fetches original URL and performs window.location to it. Secrets/Integration setup: Set Lovable Cloud Secrets SUPABASE_URL and SUPABASE_KEY (see next prompt). Include this message for Lovable (copy/paste into Chat Mode): ``` // Create files below. Use a minimal React + vanilla bundling that Lovable project supports. // index.html: mount point and script // src/index.jsx: render // src/App.jsx: form to create slug (optional custom slug) and display list // src/SupabaseClient.js: initialize supabase using env vars (from Secrets via process.env.SUPABASE_URL etc.) // public/r.html: read ?slug= from location.search, call Supabase REST to fetch url, then window.location.href = originalUrl or show 404

// Be explicit about file contents and imports. Use fetch to call Supabase REST endpoints (no server code).
// Use simple UUID/slug generation fallback if not provided. Ensure links are created with unique slug check.


 

Prompt 2:
Goal: Configure Secrets and give instructions to create the Supabase table.
Exact files to modify: none (instructions only).
Acceptance criteria: Done when Secrets SUPABASE_URL and SUPABASE_KEY exist in Lovable Cloud Secrets UI and Supabase has a table named "links" with columns: id (uuid), slug (text, unique), url (text), created\_at (timestamp default now()).
Secrets/Integration setup steps (pasteable message for Lovable Chat Mode to show to user):

// Tell user to open Lovable Cloud > Secrets and add:
// SUPABASE_URL -> your Supabase project URL
// SUPABASE_KEY -> anon/public or service_role key (anon ok for demo; for production use server-side functions)

// Also instruct the user to create the 'links' table in the Supabase SQL editor with:
// -- SQL to run in Supabase UI
// CREATE TABLE public.links (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), slug text UNIQUE NOT NULL, url text NOT NULL, created_at timestamp with time zone DEFAULT now());


 

<h3>How to verify in Lovable Preview</h3>

&nbsp;

<ul>
  <li><b>Open Preview</b>, submit a long URL. You should get a short slug displayed.</li>
  <li>Click the provided link which opens public/r.html?slug=XYZ — the page should redirect you to the original URL (or show a 404 message if missing).</li>
</ul>

&nbsp;

<h3>How to Publish / re-publish (if applicable)</h3>

&nbsp;

<ul>
  <li><b>Publish in Lovable</b> to make the app live on the Lovable-hosted domain for the SPA and r.html redirect page (client-side redirects only).</li>
  <li>For root-path short URLs (example.com/abc) or server-side redirects, <b>export to GitHub from Lovable</b> and deploy to Vercel/Netlify/Supabase Edge Functions. This step is outside Lovable and requires standard deployment setup on those platforms.</li>
</ul>

&nbsp;

<h3>Common pitfalls in Lovable (and how to avoid them)</h3>

&nbsp;

<ul>
  <li><b>Expecting server-side redirects in Preview:</b> Preview can only demonstrate client-side r.html redirects. Real short-path redirects need server/hosting config after GitHub export.</li>
  <li><b>Secrets not set:</b> If SUPABASE\_URL/KEY are missing, fetch calls will fail — set them in Lovable Cloud Secrets UI before Preview.</li>
  <li><b>Using service_role key in client:</b> Don’t expose service_role in client-side builds. Use anon/public key for demo; for secure writes use serverless functions after export.</li>
</ul>

&nbsp;

<h3>Validity bar</h3>

&nbsp;

<p><b>Accurate within Lovable constraints:</b> All build and preview steps work fully inside Lovable using Chat Mode edits, Preview, Publish, and Secrets UI. Production root-path redirects require GitHub export + external host (outside Lovable).</p>

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

How to add DB-backed rate limiting and temporary IP blocks to /api/shorten

This prompt helps an AI assistant understand your setup and guide to build the feature

AI AI Prompt

How to add Click Webhook Delivery to a Lovable URL shortener

This prompt helps an AI assistant understand your setup and guide to build the feature

AI AI Prompt

How to auto-expire & soft-archive short links

This prompt helps an AI assistant understand your setup and guide to build the feature

AI AI Prompt

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation
Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

Best Practices for Building a URL shortener app with AI Code Generators

Build the shortener as a small API + redirect service (serverless functions) backed by a real DB (e.g., Supabase). Use Lovable chat edits and file diffs to create API routes, set dependencies in package.json, store secrets with Lovable Secrets UI (SUPABASE_URL, SUPABASE_KEY), test in Preview, then Publish or sync to GitHub for CI. Keep slug generation deterministic and collision-resistant (nanoid), record analytics lightly, and validate user input and rate limits to avoid abuse.

 

Practical step-by-step (what to do inside Lovable)

 

  • Create files with Chat Mode: add package.json, an API handler file (e.g., api/create.js) and a redirect handler (api/r/[id].js).
  • Add dependencies by editing package.json so Lovable installs them on build (no terminal needed).
  • Set Secrets using Lovable Secrets UI: SUPABASE_URL and SUPABASE_KEY (service role key if you need inserts from server code).
  • Provision DB in Supabase (via their UI): create table short_urls with columns id TEXT primary key, original_url TEXT, created\_at TIMESTAMP.
  • Preview in Lovable to test endpoints; use Publish or GitHub sync to deploy to production.

 

Essential code (minimal working example using Supabase + nanoid)

 

// package.json
{
  "name":"lovable-shortener",
  "version":"1.0.0",
  "type":"module",
  "dependencies":{
    "@supabase/supabase-js":"^2.0.0",
    "express":"^4.18.2",
    "nanoid":"^4.0.0"
  }
}
// api/create.js
import express from "express";
import { createClient } from "@supabase/supabase-js";
import { customAlphabet } from "nanoid";

// Load secrets via process.env (set these in Lovable Secrets UI)
const SUPABASE_URL = process.env.SUPABASE_URL;
const SUPABASE_KEY = process.env.SUPABASE_KEY;

const app = express();
app.use(express.json());

const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
const nanoid = customAlphabet("0123456789abcdefghijklmnopqrstuvwxyz", 7);

app.post("/", async (req, res) => {
  // Validate input URL
  const { url } = req.body;
  if (!url || !/^https?:\/\//.test(url)) return res.status(400).json({ error: "invalid url" });

  // generate id and insert, retry on rare collision
  for (let i = 0; i < 3; i++) {
    const id = nanoid();
    const { error } = await supabase.from("short_urls").insert({ id, original_url: url });
    if (!error) {
      return res.json({ id, short: `${process.env.BASE_URL || ""}/r/${id}` });
    }
    // if unique constraint violated, loop and retry
  }
  res.status(500).json({ error: "could not create short url" });
});

export default app;
// api/r/[id].js
import express from "express";
import { createClient } from "@supabase/supabase-js";

const SUPABASE_URL = process.env.SUPABASE_URL;
const SUPABASE_KEY = process.env.SUPABASE_KEY;

const app = express();
const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);

app.get("/:id", async (req, res) => {
  const { id } = req.params;
  const { data, error } = await supabase.from("short_urls").select("original_url").eq("id", id).single();
  if (error || !data) return res.status(404).send("Not found");
  // Optionally record a click asynchronously
  res.redirect(data.original_url);
});

export default app;

 

Operational & security best practices

 

  • Secrets: Always set SUPABASE_URL and SUPABASE_KEY via Lovable Secrets UI, never commit keys to GitHub.
  • Rate limits & abuse: enforce per-IP limits and CAPTCHAs if public—implement in API code or with a WAF.
  • Collision safety: use nanoid (or longer length) and perform insert retries on conflict.
  • Analytics: store minimal click logs asynchronously to avoid slowing redirects.
  • Preview first: test create + redirect flows in Lovable Preview. If you need more control (migrations, CI), sync to GitHub and run DB migrations from Supabase UI or CI pipeline.

 


Recognized by the best

Trusted by 600+ businesses globally

From startups to enterprises and everything in between, see for yourself our incredible impact.

RapidDev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with.

They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

Arkady
CPO, Praction
Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost.

He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Donald Muir
Co-Founder, Arc
RapidDev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space.

They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Mat Westergreen-Thorne
Co-CEO, Grantify
RapidDev is an excellent developer for custom-code solutions.

We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Emmanuel Brown
Co-Founder, Church Real Estate Marketplace
Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 

This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Samantha Fekete
Production Manager, Media Production Company
The pSEO strategy executed by RapidDev is clearly driving meaningful results.

Working with RapidDev has delivered measurable, year-over-year growth. Comparing the same period, clicks increased by 129%, impressions grew by 196%, and average position improved by 14.6%. Most importantly, qualified contact form submissions rose 350%, excluding spam.

Appreciation as well to Matt Graham for championing the collaboration!

Michael W. Hammond
Principal Owner, OCD Tech

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.