/lovable-issues

Configuring SPA Fallback Pages in Lovable Projects

Explore why fallback pages matter for Lovable SPAs, how to set up fallback routing, and best practices for single-page app performance.

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 Fallback Pages Are Needed in Lovable SPAs

 
Understanding Fallback Pages in Lovable SPAs
 

  • Single-page applications, or SPAs, load most of their resources once and then update the content on the fly without refreshing the whole page. This design makes them feel very smooth and “lovable.”
  • Sometimes, however, the application might not know what to display for a certain URL or route. In these cases, the fallback page acts as a safety net to handle unexpected situations.
  • The fallback page is like a friendly guide—it catches any navigation that doesn’t match an existing part of the website. It prevents users from seeing confusing errors.
  • Imagine a visitor clicks a link that the app doesn’t recognize. Without a fallback, the visitor might end up staring at an empty screen or a generic error message. A fallback page gives clear guidance on what to do next.
  • The fallback mechanism also comes into play when parts of the app are loaded only when needed (lazy loading). If there’s an issue with loading the desired content, the fallback page ensures the user still sees something useful instead of blank space.

 
How the Fallback Process Works in a SPA
 

  • When a visitor enters an unknown URL or when dynamic content has trouble loading, the application checks if it can serve a known view. If not, it automatically switches to showing the fallback page.
  • This process makes the application more resilient. The fallback page informs the user that something unexpected happened, rather than just showing a browser error.
  • This safety net is essential in applications that depend on client-side routing, where the browser does not perform a full page reload with each click.

 
Example of a Fallback Code Snippet in a SPA
 


/_ Imagine this is part of the routing logic in a SPA _/
function handleRoute(route) {
  if (routes[route]) {
    // Load and display the correct page
    displayPage(routes[route]);
  } else {
    // Unknown route: fall back to the safe page
    displayFallbackPage();
  }
}
  • This code shows a very simple logic used in SPAs: when a user navigates somewhere, the app checks if the route exists in its internal list.
  • If the route isn’t found, the app calls a function to display a fallback page instead.
  • The fallback page is designed to be helpful—often suggesting a return to the home page or providing a clear way to navigate away from the error.

 
Why Fallback Pages Are Important for Users
 

  • They ensure a seamless experience, even when things don’t go as planned, by preventing the display of raw errors or blank screens.
  • They offer guidance through navigation mishaps, making the application feel robust and well-designed.
  • They promote trust and usability; users enjoy a graceful safety net that helps maintain a consistent and friendly experience.

How to Configure SPA Fallback Routing in Lovable

 
Step One: Create the Configuration File for Fallback Routing
 

  • In the Lovable code editor, create a new file called lovable.config.json in the root directory of your project. This file is where Lovable looks for custom configuration rules.
  • Paste the following code into lovable.config.json. This code tells Lovable to serve the index.html file no matter what URL a user visits (unless the file exists in the designated folder). In this example, it is assumed that your static files (like index.html) are in a folder named public:
    
    {
      "routes": [
        {
          "src": "/public/(.\*)",
          "dest": "/public/$1"
        },
        {
          "src": "/(.\*)",
          "dest": "/public/index.html"
        }
      ]
    }
        
  • Save the file. This configuration means that any direct file reference (for example, an image or CSS file in public) will be delivered as expected. Any other route (for example, /about or /contact) will return index.html. This is the core of the fallback routing for your single-page application (SPA).

 
Step Two: Organize Your Application Files
 

  • Ensure that your main HTML file, typically named index.html, is placed inside a folder called public in your project root. This helps the configuration correctly reference the file.
  • Double-check that all your static assets (such as CSS, JavaScript, images) are also inside the public folder or in appropriate subdirectories. This way, the first route rule (for explicit static files) will work without a hitch.

 
Step Three: Review and Finalize Your Code Changes
 

  • Open your project’s file explorer within Lovable and verify that the new file lovable.config.json is located at the root level of your project.
  • Confirm that your folder structure looks like this:
    
    /your-project-root
      /public
        index.html
        (other assets)
      lovable.config.json
        
  • If your project already includes a custom server code file, no changes are needed there for fallback routing because the configuration file takes care of routing behaviour when no terminal or command-line access is available.

 
Step Four: Understand the Fallback Routing Logic
 

  • The first rule in lovable.config.json checks if the URL starts with /public/. If it does, then Lovable will serve the requested static file.
  • The second rule is a catch-all. It captures every route (/(.\*)) and directs it to /public/index.html. This is essential for single-page applications because it lets the client-side code handle routing, even when a user refreshes the page or directly enters a URL.
  • This ensures that the application does not return a "404 Not Found" error when a user navigates to a URL that is not a physical file but a route handled by your JavaScript routing library.

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

Best Practices for SPA Fallback Routing in Lovable

 
Configuring Fallback Routing in Lovable for Single-Page Applications
 

  • Create a new file in your project’s root folder named server.js. This file will control how your application handles all incoming requests.
  • In Lovable’s code editor, open server.js and add the following code. This code uses a popular module to serve your files and then “falls back” to sending your main index.html when no other file is found. This is essential for Single-Page Applications (SPA) because it allows the client-side JavaScript to manage routing:
    
    // server.js
    const express = require('express');
    const path = require('path');
    const app = express();
    
    

    // This tells the server where your static files are located.
    // Create a folder named 'public' in your project and place your index.html and other assets there.
    app.use(express.static(path.join(__dirname, 'public')));

    // Fallback Routing
    // Any route that is not recognized as a static file will trigger this middleware.
    // The server sends back index.html, allowing your SPA's client-side routing to take over.
    app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
    });

    // This starts your server on port 3000 (or a port defined in the environment).
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => {
    console.log(Server is running on port ${PORT});
    });



  • Make sure the order of the code is exactly as shown. The static file serving must come before the fallback route so that your existing files (like CSS, JS, images) are served properly.

 
Defining Your Project Dependencies
 

  • Create a new file called package.json in the root of your project. This file tells Lovable which external code modules your app requires.
  • Open package.json in the code editor and paste the following code. Note that this lists the dependency for the server module we used. Lovable will use this file to manage your dependencies automatically since it does not provide a terminal for manual installation commands:
    
    {
      "name": "lovable-spa",
      "version": "1.0.0",
      "description": "A Single-Page Application with fallback routing for Lovable",
      "main": "server.js",
      "dependencies": {
        "express": "^4.18.0"
      },
      "scripts": {
        "start": "node server.js"
      }
    }
        
  • This file ensures that when your project runs, Lovable knows to include the Express module required in your server.js file.

 
Placing Your SPA Entry Point
 

  • Create a new folder named public in your project’s root directory. This folder will store all static assets for your SPA.
  • Within the public folder, ensure that you have an index.html file. This file acts as the starting point for your application and will be served for all routes not recognized by your backend logic.
  • The fallback route in server.js will always point to this index.html, allowing your client-side JavaScript to manage the navigation and display the correct views.

 
Best Practices and Troubleshooting Tips
 

  • Always ensure the static file middleware (the part that serves files from the public folder) is placed before the fallback route. This prevents valid asset requests from being intercepted by the fallback.
  • If your SPA does not load correctly on refresh errors, double-check that the path to index.html in the fallback route is accurate.
  • Use clear and descriptive file names. Keeping your server and configuration files like server.js and package.json updated and error-free is key to a maintainable project.
  • When adding new features or routes, always test locally by navigating to different URLs to confirm that the correct views are being delivered by the client-side application.

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev 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.

CPO, Praction - Arkady Sokolov

May 2, 2023

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!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev 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.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-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.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

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!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022