/lovable-issues

Adding Custom Routes in Lovable Without Breaking Navigation

Learn why navigation in Lovable breaks with custom routes and discover best practices for adding routes seamlessly.

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

Why Navigation Breaks When Adding Custom Routes in Lovable

Navigation breaks because the new route patterns or handlers you added conflict with how the app’s client-side router, the hosting environment (Lovable Preview/Cloud), and any server/runtime routes expect to resolve URLs. Common failure modes are route ordering or wildcard/catch-all collisions, links that force full-page loads into a server route that doesn’t exist in Preview, basePath/hydration mismatches, or routes that require build-time or server configuration that isn’t running inside Lovable’s preview environment.

 

Common root causes (what actually breaks)

 

 

Paste-into-Lovable prompts to diagnose where navigation is breaking

 

// Prompt A: Repo-wide routing scan
// Ask Lovable to find router files and list declared routes
Please search the repository for routing-related files and tokens: "BrowserRouter", "Routes", "Route", "react-router", "next/router", "app/", "pages/", "router.ts", "routes.tsx", "pages/_app", "next.config.js". For each match, list the file path and copy the relevant route definitions or router setup (20–200 lines) and highlight any catch-all (wildcard/:slug/*) or dynamic patterns.
// Prompt B: Preview runtime errors and network traces
// Ask Lovable to run Preview and capture console + network info for a failing nav
Open the Lovable Preview for this project. Navigate to the route that breaks and capture the browser console errors and the network tab responses for the failing requests (status codes and response bodies). Paste those logs here. If the app uses client-side routing, click the in-app link that fails and capture the same info.
// Prompt C: Add a non-destructive runtime route-map (diagnostic)
// Make a temporary debug change to show which routes the router recognizes
If this repo uses src/App.tsx or src/router.tsx, create a temporary debug component that renders the current route match and all route patterns detected (render-only, no navigation changes). Update src/App.tsx to mount a visible "Route diagnostics" panel at the top of the app during Preview. Include console.log of window.location and the router match. Keep the change flagged as temporary in a comment.

Still stuck?
Copy this prompt into ChatGPT and get a clear, personalized explanation.

This prompt helps an AI assistant understand your setup and guide you through the fix step by step, without assuming technical knowledge.

AI AI Prompt

How to Add Custom Routes Without Breaking Navigation in Lovable

 

Direct answer

 

Add your custom routes by editing the app’s router entry inside Lovable Chat Mode (for example update src/App.tsx’s <Routes> block or create a new pages file for Next.js), make sure the router has a SPA-friendly fallback (catch-all) and consistent basename/history, then use Lovable Preview to confirm navigation works. If you need server rewrites for production, export to GitHub and add those hosting rewrites outside Lovable.

 

Step-by-step Lovable prompts to paste into Chat Mode

 

  • React Router (typical SPA) — update router and add a fallback

 

Please make these changes in the project files.

1) Update src/App.tsx — modify the <Routes> block to explicitly add the new custom route and a safe fallback. Replace the existing <Routes> section with the following (keep surrounding imports and BrowserRouter):

// // // start replacement
<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/about" element={<About />} />
  <Route path="/custom/*" element={<CustomRoot />} /> // // // Custom route root for nested/custom pages
  <Route path="*" element={<Navigate to="/" replace />} /> // // // SPA-friendly fallback
</Routes>
// // // end replacement

2) Create src/components/CustomRoot.tsx — a small wrapper that mounts nested/custom pages and preserves router history:

// // // create file src/components/CustomRoot.tsx
import { Routes, Route } from "react-router-dom";
// // // define simple nested routes inside custom
export default function CustomRoot() {
  return (
    <Routes>
      <Route path="/" element={<CustomIndex />} />
      <Route path="feature" element={<CustomFeature />} />
      <Route path="*" element={<Navigate to="/" replace />} />
    </Routes>
  );
}
// // // end file

3) Ensure all internal navigation uses react-router Link/NavLink or useNavigate and use relative paths for nested routes (e.g., to navigate to feature from /custom use navigate("feature") or <Link to="feature" />).

4) After edits, open Lovable Preview and walk through links: root, /custom, /custom/feature to confirm navigation does not reload or 404.

 

  • If your app is Next.js (file-based) — add pages or app routes inside Lovable

 

Please create the following file(s) in the Next.js pages/app folders.

1) If using pages router — create pages/custom/[...slug].tsx:

// // // create file pages/custom/[...slug].tsx
import { useRouter } from "next/router";
// // // render your custom page or route-match
export default function CustomCatchAll() {
  const { query } = useRouter();
  // // // render based on query.slug
  return <div>Custom page: {JSON.stringify(query.slug)}</div>;
}
// // // end file

2) If using app router — create app/custom/[...slug]/page.tsx with the desired UI.

3) Preview in Lovable. Next.js routing is handled by the framework so test client navigation and server-rendered navigations.

4) If you need custom rewrite rules for production hosts (e.g., Netlify/_redirects or Vercel rewrites), export the repo to GitHub from Lovable and add those host-specific configs outside Lovable (this is outside Lovable and requires deployment config on your host).

 

Notes on using Lovable features while you work

 

  • Use Chat Mode edits and file diffs to update files above; Preview to test navigation immediately.
  • If you must change hosting rewrite rules (to avoid 404 on browser reload for SPA routes), use Lovable’s GitHub export/sync and apply the host-specific rewrite configuration on your deployment provider (this step is outside Lovable).
  • Do not run terminal commands inside Lovable; any build/deploy host adjustments go via GitHub export or your host’s dashboard.

 

Best Practices for Managing Custom Routes in Lovable

Keep a single source of truth for routes (a small routes manifest), wire your app’s router to read routes from that file, add a safe fallback and route-aware link helper, and store any runtime base-path or API-route flags in Lovable’s Secrets UI so previews/publishes behave the same as production.

 

Practical step-by-step Lovable prompts to implement this

 

Paste each of the following prompts into Lovable’s chat (one at a time). They tell Lovable exactly which files to create/change. Use Preview to verify and Publish when ready. If any change requires a local build or custom server that can’t be done inside Lovable, I’ll mark it “outside Lovable (terminal required)” and suggest exporting to GitHub.

  • Prompt — create a centralized routes manifest
    <p>Tell Lovable to create src/routes.ts (or src/routes/index.ts) and export a single array of route objects. Include a suggested shape and comments explaining fields.</p>
    
    \`\`\`text
    

    // Please create file src/routes.ts with the following content:
    // This is the single source of truth for in-app routes.
    // Each route object contains: id, path, component path, and optional exact flag.

    const routes = [
    { id: 'home', path: '/', component: './pages/Home' },
    { id: 'about', path: '/about', component: './pages/About' },
    // Add custom routes here
    // Example custom route:
    // { id: 'app-custom', path: '/custom/:id', component: './pages/Custom' },
    ];

    export default routes;

    
      </li>
    
      <li><b>Prompt — wire the router to the manifest</b>
    
        <p>Ask Lovable to update your router entry point (e.g., src/App.tsx or src/main.tsx). Tell it to import src/routes.ts, dynamically import or statically import components per your app style, and add a catch-all fallback route that redirects to '/'. Point Lovable to the exact file and the <Routes> or router initialization block to update.</p>
    
        ```text
    // Update src/App.tsx (or the file that contains your <Routes> block).
    // Replace hard-coded route definitions with imports from src/routes.ts.
    // Add a fallback <Route path="*"> that redirects to '/' or shows NotFound component.
    // Use existing router API (React Router, Next-style, or your app's router) — keep the app's router usage intact, only replace route list with the manifest.
    
  • Prompt — add route helpers so navigation always uses canonical paths
    <p>Create src/lib/routeHelpers.ts with small helpers for building URLs from route ids and params. This prevents ad-hoc string concatenation across the codebase.</p>
    
    \`\`\`text
    

    // Create src/lib/routeHelpers.ts
    // export function pathFor(routeId, params) { /_ build path from routes manifest / }
    // export function linkProps(routeId, params) { /
    return { href, to } depending on router _/ }
    // Use this helper across the app instead of hard-coded strings.

    
      </li>
    
      <li><b>Prompt — support a configurable base path via Lovable Secrets</b>
    
        <p>Ask Lovable to add docs/comments and code that reads a BASE_PATH from environment and prepends it in route helpers and router base configuration. Tell Lovable to reference both Vite/React build-time patterns and fallback to process.env for common frameworks. Then instruct to set that value in Lovable’s Secrets UI.</p>
    
        ```text
    // Update src/lib/routeHelpers.ts to read basePath from:
    // import.meta.env.VITE_BASE_PATH || process.env.REACT_APP_BASE_PATH || ''
    // Ensure all generated links include basePath.
    // Then instruct the user to open Lovable's Secrets UI and add a secret named BASE_PATH with the desired value.
    
  • Prompt — add a NotFound component and make it safe
    <p>Create src/pages/NotFound.tsx and wire it to the fallback route. Include a friendly link back to the home route using the routeHelpers created above.</p>
    
    \`\`\`text
    

    // Create src/pages/NotFound.tsx with a simple UI and a link that uses routeHelpers.pathFor('home')

    
      </li>
    
      <li><b>Prompt — run a quick route audit</b>
    
        <p>Ask Lovable to scan the repo for any hard-coded strings that look like routes (e.g., "/profile", "/dashboard") and list them in the chat. For each occurrence, suggest replacing with routeHelpers.pathFor or linkProps. Lovable should create file diffs for replacing a few simple cases.</p>
    
        ```text
    // Search project for string literals that look like paths (start with '/')
    // Produce a report and suggested code edits for the top matches.
    
  • Prompt — when a change requires custom server or build scripts (outside Lovable)
    <p>If your app needs a custom server, base-path rewrites at build time, or special adapter changes, tell Lovable to export the repo to GitHub and add a note: “outside Lovable (terminal required) — run local/build steps.” Lovable should create a commit and prepare a GitHub export.</p>
    
    \`\`\`text
    

    // If a step requires terminal, prepare a GitHub export and add a README note:
    // "This change requires running: npm run build && npm run start with custom server. Execute locally or CI."
    ```

 

Essential practices to follow after implementing

 

  • Use Preview to validate routing across base-paths
  • Set BASE\_PATH (or similar) in Lovable Secrets UI so Preview/Publish match production
  • Keep the routes manifest minimal and human-readable — avoid branching logic inside it
  • Replace hard-coded path strings incrementally using the route audit diffs
  • Export to GitHub only when you need terminal work; mark those changes clearly

 

Follow these prompts in Lovable chat one-by-one. Use Preview to test, and Publish when stable. If you want, paste one of the prompts now and I’ll produce the exact file contents for that specific file to paste into Lovable.


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.