/how-to-build-lovable

How to build Digital downloads with Lovable?

Learn how to build digital downloads with Lovable using our step-by-step guide. Set up, design, and launch your engaging digital products with ease.

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 Digital downloads with Lovable?

 
Setting Up Your Digital Downloads Project in Lovable
 

  • Open your Lovable dashboard and create a new project. Name it something like Digital Downloads.
  • Since Lovable does not include a terminal, all dependency installations are handled in code. We will add our dependency configurations in the Lovable configuration file.
  • Create a new file named lovable.config.js in your project’s root directory. This file will list the external libraries your project requires.

Create the file lovable.config.js and add the following code:


module.exports = {
  dependencies: {
    crypto: "npm:crypto"
    // If you need to add other libraries, include them here in the same format.
  }
};

 
Creating the Main Application File
 

  • Create or open your main application file. For this guide, let’s assume it is named app.js.
  • We will insert our code here to handle digital download requests. This file will configure server routes and functions.

Add the following snippet at the top of app.js to import your dependencies and set up a basic server. Make sure to include this snippet at the very start of your file:


const http = require('http');
const crypto = require('crypto');

// Basic server setup using Lovable's built-in system
const port = process.env.PORT || 8080;

 
Implementing Secure Download Link Generation
 

  • Within app.js, add a function to generate secure download links. This function will create a token based on the user and product information.

Insert the following code snippet after your dependency imports:


function createSecureToken(userId, productId) {
  // Combine user, product, and timestamp details for security
  const data = userId + ":" + productId + ":" + Date.now();
  return crypto.createHash('sha256').update(data).digest('hex');
}

function generateDownloadLink(userId, productId) {
  const token = createSecureToken(userId, productId);
  // For simplicity, we assume the token is stored or validated in our download handler
  return `https://yourlovabledomain.com/download?token=${token}`;
}

 
Setting Up the Download Request Handler
 

  • Create a new file named downloadHandler.js in your project’s root directory. This file will handle incoming download requests and validation.
  • The download process includes validating the token, ensuring it has not expired, and then serving the file securely to the user.

Create downloadHandler.js and add the following code:


const http = require('http');
const url = require('url');
// In a real scenario, a file path lookup and token validation mechanism would be implemented

function validateToken(token) {
  // Placeholder for token validation logic
  // Typically, you’d check a database for token existence and expiration
  return token && token.length === 64;
}

function getFilePathFromToken(token) {
  // Dummy function – in real usage retrieve the file path associated with the token
  return './downloads/sample-file.zip';
}

function handleDownloadRequest(req, res) {
  const queryData = url.parse(req.url, true).query;
  const token = queryData.token;
  if (validateToken(token)) {
    const filePath = getFilePathFromToken(token);
    // Send the file for download. In Lovable, you may use built-in file streaming.
    res.writeHead(200, {
      'Content-Type': 'application/octet-stream',
      'Content-Disposition': 'attachment; filename="download.zip"'
    });
    // For demonstration, we simulate file data.
    res.end("Simulated file content.");
  } else {
    res.writeHead(403, {'Content-Type': 'text/plain'});
    res.end('Invalid or expired download link.');
  }
}

module.exports = {
  handleDownloadRequest
};

 
Integrating the Download Handler with Your Server
 

  • Return to your app.js file.
  • Import the download handler and add a route for handling download requests.

Insert the following code snippet below your previously inserted functions in app.js:


const { handleDownloadRequest } = require('./downloadHandler');

const server = http.createServer((req, res) => {
  const urlParts = req.url.split('?')[0];
  if (urlParts === '/download') {
    handleDownloadRequest(req, res);
  } else {
    // Default response for other routes
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('

Welcome to the Digital Downloads Service

'); } }); server.listen(port, () => { console.log(`Server running at http://0.0.0.0:${port}/`); });

 
Building the Front-End for Requesting Downloads
 

  • Create a new file named index.html in your project’s root directory. This file will serve as the landing page where users can request digital downloads.
  • Add a simple form or button that simulates a download request, such as linking to a generated download URL.

For example, add the following content to index.html:




  
    
    Digital Downloads
  
  
    

Digital Downloads

Click the button below to get your download.

 
Testing Your Digital Downloads Feature
 

  • Save all your files (lovable.config.js, app.js, downloadHandler.js, and index.html).
  • Click on the Run button in Lovable to start your application.
  • Access your application via the provided URL and click on the button in index.html to test the download functionality.

 
Finalizing and Sharing Your Project
 

  • After testing, review your code and ensure that the token generation and validation logic is integrated with your actual user purchase system.
  • Make any adjustments needed for production, such as connecting to your database and implementing secure file access.
  • Share the URL provided by Lovable to allow users to access your digital downloads service.

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 Build a Secure Digital Downloads API with Lovable


const express = require('express');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

const app = express();

const digitalDownloads = {
  'lovable001': {
    title: 'Lovable Premium Digital Album',
    filePath: path.join(\__dirname, 'downloads', 'lovable_album.zip'),
    fileSize: fs.existsSync(path.join(\__dirname, 'downloads', 'lovable_album.zip')) 
              ? fs.statSync(path.join(\__dirname, 'downloads', 'lovable_album.zip')).size 
              : 0
  }
};

function generateToken(productId) {
  const secret = 'SuperSecretSaltForLovable';
  return crypto.createHash('sha256').update(productId + secret).digest('hex');
}

app.get('/api/download/:productId', (req, res) => {
  const { productId } = req.params;
  const product = digitalDownloads[productId];

  if (!product) {
    return res.status(404).json({ error: 'Product not found' });
  }

  const userToken = req.query.token;
  const validToken = generateToken(productId);

  if (!userToken || userToken !== validToken) {
    return res.status(403).json({ error: 'Unauthorized access' });
  }

  res.setHeader('Content-Length', product.fileSize);
  res.setHeader('Content-Disposition', `attachment; filename="${path.basename(product.filePath)}"`);

  const readStream = fs.createReadStream(product.filePath);
  readStream.on('error', () => res.status(500).end('Error reading file'));
  readStream.pipe(res);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

How to Generate Pre-signed Download URLs with Lovable


import express from 'express';
import AWS from 'aws-sdk';
import crypto from 'crypto';
import dotenv from 'dotenv';

dotenv.config();
const app = express();

AWS.config.update({
  region: process.env.AWS\_REGION
});

const s3 = new AWS.S3();
const digitalProducts = {
  "lovable1001": { s3Key: "products/lovable\_album.zip", title: "Lovable Premium Digital Album" }
};

const generateToken = (productId) =>
  crypto.createHmac("sha256", process.env.TOKEN\_SECRET)
    .update(productId)
    .digest("hex");

app.get('/api/presign/:productId', async (req, res) => {
  const { productId } = req.params;
  const product = digitalProducts[productId];
  if (!product) {
    return res.status(404).json({ error: "Product not found" });
  }

  const { token } = req.query;
  if (!token || token !== generateToken(productId)) {
    return res.status(403).json({ error: "Unauthorized access" });
  }

  const params = {
    Bucket: process.env.S3\_BUCKET,
    Key: product.s3Key,
    Expires: 600 // URL valid for 10 minutes
  };

  try {
    const signedUrl = await s3.getSignedUrlPromise("getObject", params);
    res.json({ downloadUrl: signedUrl });
  } catch (error) {
    res.status(500).json({ error: "Error generating download URL" });
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

How to build a secure digital download API with Lovable


"use strict";
const express = require('express');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const sqlite3 = require('sqlite3').verbose();

const app = express();
const PORT = process.env.PORT || 3000;
const secret = "LovableDownloadSecret";

const db = new sqlite3.Database(':memory:');
db.serialize(() => {
  db.run(\`CREATE TABLE downloads (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    productId TEXT NOT NULL,
    ip TEXT NOT NULL,
    timestamp INTEGER NOT NULL
  )\`);
});

const digitalProducts = {
  "lovable2002": {
    title: "Lovable Deluxe Digital Cover",
    filePath: path.join(\__dirname, 'assets', 'lovable_deluxe.zip')
  }
};

function createToken(productId) {
  return crypto.createHmac('sha256', secret).update(productId).digest('hex');
}

function logDownload(productId, ip) {
  const stmt = db.prepare("INSERT INTO downloads (productId, ip, timestamp) VALUES (?, ?, ?)");
  stmt.run(productId, ip, Date.now());
  stmt.finalize();
}

app.get('/api/download/log/:productId', (req, res) => {
  const { productId } = req.params;
  const token = req.query.token;
  const expectedToken = createToken(productId);

  if (!digitalProducts[productId]) {
    return res.status(404).json({ error: "Product not found" });
  }
  
  if (!token || token !== expectedToken) {
    return res.status(403).json({ error: "Invalid token" });
  }
  
  const product = digitalProducts[productId];
  fs.access(product.filePath, fs.constants.R\_OK, (err) => {
    if (err) return res.status(500).json({ error: "File access error" });
    
    logDownload(productId, req.ip);
    res.setHeader('Content-Disposition', `attachment; filename="${path.basename(product.filePath)}"`);
    const stream = fs.createReadStream(product.filePath);
    stream.on('error', () => res.status(500).end("Error reading file"));
    stream.pipe(res);
  });
});

app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

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 Digital downloads with AI Code Generators

 
Understanding Digital Downloads with AI Code Generators
 

  • This guide explains how to build and package digital downloads using AI-based code generators.
  • Digital downloads can include themes, plugins, snippets, templates, or any software tool delivered as a file.
  • AI code generators help automate code creation, making the development process faster and more efficient.

 
Prerequisites
 

  • A basic computer with internet access.
  • A modern web browser.
  • Access to an AI code generation tool (such as GitHub Copilot, OpenAI Codex, or similar).
  • Basic understanding of how files and directories work on your computer.
  • A text editor like VS Code, Sublime Text, or Notepad++.
  • A digital marketplace or distribution platform account if you plan to sell the download.

 
Planning Your Digital Download Project
 

  • Identify the type of digital download you want to create (e.g., website template, code snippet library, plugin).
  • Outline the features or functionalities you intend to include.
  • Decide on the file structure and documentation that will accompany your digital download.
  • Set clear objectives and outcomes to ensure the project meets your audience’s needs.

 
Generating Code with an AI Code Generator
 

  • Open your text editor and start a new project folder for your digital download.
  • Launch your AI code generation tool within your development environment.
  • Describe the functionality needed, for example: "Create a layout template for a responsive website".
  • Review and refine the generated code to meet your specific project requirements.
  • Below is an example snippet generated by an AI tool for a simple HTML template:
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Responsive Template</title>
      <style>
        body { font-family: Arial, sans-serif; margin: 0; padding: 0; }
        .header { background: #333; color: #fff; padding: 20px; text-align: center; }
        .content { padding: 20px; }
      </style>
    </head>
    <body>
      <div class="header">Welcome to My Digital Download</div>
      <div class="content">
        <p>This is a responsive HTML template generated using an AI code tool.</p>
      </div>
    </body>
    </html>
        
  • Ensure that you test and validate the generated code across different devices if it is a front-end template.

 
Organizing Code and Documentation
 

  • Create a clear folder structure to separate source code, assets (like images or styles), and documentation.
  • Include a README file that explains the functionalities, how to install, and how to use your digital download.
  • Prepare a changelog or update log file that tracks modifications and enhancements over time.
  • Consider adding inline code comments and external documentation to help users understand the code better.

 
Testing Your Digital Download
 

  • Manually test the functionality by opening files in a web browser or running relevant scripts.
  • Use automated testing tools where applicable to verify code validity and functionality.
  • Gather feedback from beta testers or early users to identify any issues or improvements needed.

 
Securing and Packaging Your Digital Download
 

  • Review your code for any sensitive information such as API keys or credentials before packaging.
  • Minify or obfuscate code if needed to protect intellectual property while maintaining functionality.
  • Package your digital download as a ZIP file or another common archive format for easy distribution.
  • Include a license file that clearly states how your digital download may be used or modified.
  • Example of a basic LICENSE file content:
    
    MIT License
    
    

    Copyright (c) [Year] [Your Name]

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction...


 
Deploying and Distributing Your Digital Download
 

  • Choose a distribution platform such as Gumroad, Shopify, or your own website.
  • Upload your packaged file along with relevant documentation and screenshots.
  • Set pricing, licensing terms, and digital rights management options, if necessary.
  • Promote your digital download using social media, newsletters, or digital marketplaces to attract your target audience.
  • Monitor sales and user feedback to continue improving your product.

 
Maintaining and Updating Your Digital Download
 

  • Regularly review user feedback and bug reports to keep the digital download up-to-date.
  • Use version control systems (like Git) to manage changes and streamline updates.
  • Plan for future updates and enhancements, notifying your users about any significant changes.
  • Keep

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